vcsbaseplugin.cpp 36.7 KB
Newer Older
1
/**************************************************************************
con's avatar
con committed
2
3
4
**
** This file is part of Qt Creator
**
con's avatar
con committed
5
** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
con's avatar
con committed
6
**
hjk's avatar
hjk committed
7
** Contact: Nokia Corporation (info@qt.nokia.com)
con's avatar
con committed
8
**
9
**
10
** GNU Lesser General Public License Usage
11
**
hjk's avatar
hjk committed
12
13
14
15
16
17
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this file.
** Please review the following information to ensure the GNU Lesser General
** Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
18
**
con's avatar
con committed
19
** In addition, as a special exception, Nokia gives you certain additional
hjk's avatar
hjk committed
20
** rights. These rights are described in the Nokia Qt LGPL Exception
con's avatar
con committed
21
22
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
hjk's avatar
hjk committed
23
24
25
26
27
** Other Usage
**
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
con's avatar
con committed
28
** If you have questions regarding the use of this file, please contact
Tobias Hunger's avatar
Tobias Hunger committed
29
** Nokia at info@qt.nokia.com.
con's avatar
con committed
30
**
31
**************************************************************************/
hjk's avatar
hjk committed
32

con's avatar
con committed
33
#include "vcsbaseplugin.h"
34
35
#include "vcsbasesubmiteditor.h"
#include "vcsplugin.h"
36
#include "commonvcssettings.h"
37
#include "vcsbaseoutputwindow.h"
38
#include "corelistener.h"
con's avatar
con committed
39
40

#include <coreplugin/icore.h>
41
42
43
#include <coreplugin/ifile.h>
#include <coreplugin/iversioncontrol.h>
#include <coreplugin/filemanager.h>
44
45
#include <coreplugin/editormanager/editormanager.h>
#include <coreplugin/editormanager/ieditor.h>
46
47
48
49
#include <coreplugin/vcsmanager.h>
#include <projectexplorer/projectexplorer.h>
#include <projectexplorer/project.h>
#include <utils/qtcassert.h>
50
#include <utils/synchronousprocess.h>
51
#include <utils/environment.h>
con's avatar
con committed
52

53
#include <QtCore/QDebug>
54
55
#include <QtCore/QDir>
#include <QtCore/QSharedData>
56
#include <QtCore/QScopedPointer>
57
#include <QtCore/QSharedPointer>
58
59
60
#include <QtCore/QProcessEnvironment>
#include <QtCore/QTextStream>
#include <QtCore/QTextCodec>
61
62

#include <QtGui/QAction>
63
#include <QtGui/QMessageBox>
64
65
#include <QtGui/QFileDialog>
#include <QtGui/QMainWindow>
66

67
enum { debug = 0, debugRepositorySearch = 0, debugExecution = 0 };
con's avatar
con committed
68

69
70
/*!
    \namespace VCSBase
71
    \brief VCSBase plugin namespace
72
73
74
75
*/

/*!
    \namespace VCSBase::Internal
76
    \brief Internal namespace of the VCSBase plugin
77
78
    \internal
*/
79

80
namespace VCSBase {
con's avatar
con committed
81
82
namespace Internal {

83
84
85
86
87
88
89
/*!
    \struct VCSBase::Internal::State

    \brief Internal state created by the state listener and VCSBasePluginState.

    Aggregated in the QSharedData of VCSBase::VCSBasePluginState.
*/
90
91
92

struct State {
    void clearFile();
93
    void clearPatchFile();
94
95
96
97
    void clearProject();
    inline void clear();

    bool equals(const State &rhs) const;
con's avatar
con committed
98

99
100
101
102
103
104
    inline bool hasFile() const     { return !currentFile.isEmpty(); }
    inline bool hasProject() const  { return !currentProjectPath.isEmpty(); }
    inline bool isEmpty() const     { return !hasFile() && !hasProject(); }

    QString currentFile;
    QString currentFileName;
105
106
107
    QString currentPatchFile;
    QString currentPatchFileDisplayName;

108
109
110
111
112
113
114
115
116
    QString currentFileDirectory;
    QString currentFileTopLevel;

    QString currentProjectPath;
    QString currentProjectName;
    QString currentProjectTopLevel;
};

void State::clearFile()
con's avatar
con committed
117
{
118
119
120
121
    currentFile.clear();
    currentFileName.clear();
    currentFileDirectory.clear();
    currentFileTopLevel.clear();
con's avatar
con committed
122
123
}

124
125
126
127
128
129
void State::clearPatchFile()
{
    currentPatchFile.clear();
    currentPatchFileDisplayName.clear();
}

130
void State::clearProject()
con's avatar
con committed
131
{
132
133
134
    currentProjectPath.clear();
    currentProjectName.clear();
    currentProjectTopLevel.clear();
con's avatar
con committed
135
136
}

137
void State::clear()
con's avatar
con committed
138
{
139
    clearFile();
140
    clearPatchFile();
141
142
143
144
145
146
147
    clearProject();
}

bool State::equals(const State &rhs) const
{
    return currentFile == rhs.currentFile
            && currentFileName == rhs.currentFileName
148
            && currentPatchFile == rhs.currentPatchFile
149
            && currentPatchFileDisplayName == rhs.currentPatchFileDisplayName
150
151
152
153
154
            && currentFileTopLevel == rhs.currentFileTopLevel
            && currentProjectPath == rhs.currentProjectPath
            && currentProjectName == rhs.currentProjectName
            && currentProjectTopLevel == rhs.currentProjectTopLevel;
}
con's avatar
con committed
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
QDebug operator<<(QDebug in, const State &state)
{
    QDebug nospace = in.nospace();
    nospace << "State: ";
    if (state.isEmpty()) {
        nospace << "<empty>";
    } else {
        if (state.hasFile()) {
            nospace << "File=" << state.currentFile
                    << ',' << state.currentFileTopLevel;
        } else {
            nospace << "<no file>";
        }
        nospace << '\n';
        if (state.hasProject()) {
            nospace << "       Project=" << state.currentProjectName
            << ',' << state.currentProjectPath
            << ',' << state.currentProjectTopLevel;

        } else {
            nospace << "<no project>";
        }
        nospace << '\n';
    }
    return in;
}

183
184
185
186
187
188
189
190
/*!
    \class VCSBase::Internal::StateListener

    \brief Connects to the relevant signals of Qt Creator, tries to find version
    controls and emits signals to the plugin instances.

    Singleton (as not to do checks multiple times).
*/
191
192
193
194
195
196
197
198
199

class StateListener : public QObject {
    Q_OBJECT
public:
    explicit StateListener(QObject *parent);

signals:
    void stateChanged(const VCSBase::Internal::State &s, Core::IVersionControl *vc);

200
public slots:
201
202
203
204
205
206
    void slotStateChanged();
};

StateListener::StateListener(QObject *parent) :
        QObject(parent)
{
207
    Core::ICore *core = Core::ICore::instance();
208
    connect(core->editorManager(), SIGNAL(currentEditorChanged(Core::IEditor*)),
209
            this, SLOT(slotStateChanged()));
210
    connect(core->editorManager(), SIGNAL(currentEditorStateChanged(Core::IEditor*)),
211
            this, SLOT(slotStateChanged()));
212
213
    connect(core->vcsManager(), SIGNAL(repositoryChanged(QString)),
            this, SLOT(slotStateChanged()));
con's avatar
con committed
214

215
216
217
    if (ProjectExplorer::ProjectExplorerPlugin *pe = ProjectExplorer::ProjectExplorerPlugin::instance())
        connect(pe, SIGNAL(currentProjectChanged(ProjectExplorer::Project*)),
                this, SLOT(slotStateChanged()));
con's avatar
con committed
218
219
}

220
221
222
223
224
225
226
227
static inline QString displayNameOfEditor(const QString &fileName)
{
    const QList<Core::IEditor*> editors = Core::EditorManager::instance()->editorsForFileName(fileName);
    if (!editors.isEmpty())
        return editors.front()->displayName();
    return QString();
}

228
void StateListener::slotStateChanged()
con's avatar
con committed
229
{
230
231
    const ProjectExplorer::ProjectExplorerPlugin *pe = ProjectExplorer::ProjectExplorerPlugin::instance();
    const Core::ICore *core = Core::ICore::instance();
hjk's avatar
hjk committed
232
    Core::VcsManager *vcsManager = core->vcsManager();
233

234
235
236
    // Get the current file. Are we on a temporary submit editor indicated by
    // temporary path prefix or does the file contains a hash, indicating a project
    // folder?
237
    State state;
238
239
240
241
242
    Core::EditorManager *em = core->editorManager();
    if (!em || !em->currentEditor() || !em->currentEditor()->file())
        state.currentFile.clear();
    else
        state.currentFile = em->currentEditor()->file()->fileName();
243
    QScopedPointer<QFileInfo> currentFileInfo; // Instantiate QFileInfo only once if required.
244
    if (!state.currentFile.isEmpty()) {
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
        const bool isTempFile = state.currentFile.startsWith(QDir::tempPath());
        // Quick check: Does it look like a patch?
        const bool isPatch = state.currentFile.endsWith(QLatin1String(".patch"))
                             || state.currentFile.endsWith(QLatin1String(".diff"));
        if (isPatch) {
            // Patch: Figure out a name to display. If it is a temp file, it could be
            // Codepaster. Use the display name of the editor.
            state.currentPatchFile = state.currentFile;
            if (isTempFile)
                state.currentPatchFileDisplayName = displayNameOfEditor(state.currentPatchFile);
            if (state.currentPatchFileDisplayName.isEmpty()) {
                currentFileInfo.reset(new QFileInfo(state.currentFile));
                state.currentPatchFileDisplayName = currentFileInfo->fileName();
            }
        }
        // For actual version control operations on it:
        // Do not show temporary files and project folders ('#')
        if (isTempFile || state.currentFile.contains(QLatin1Char('#')))
263
264
            state.currentFile.clear();
    }
265

266
267
268
    // Get the file and its control. Do not use the file unless we find one
    Core::IVersionControl *fileControl = 0;
    if (!state.currentFile.isEmpty()) {
269
270
271
272
        if (currentFileInfo.isNull())
            currentFileInfo.reset(new QFileInfo(state.currentFile));
        state.currentFileDirectory = currentFileInfo->absolutePath();
        state.currentFileName = currentFileInfo->fileName();
273
274
275
276
277
278
279
280
        fileControl = vcsManager->findVersionControlForDirectory(state.currentFileDirectory,
                                                                 &state.currentFileTopLevel);
        if (!fileControl)
            state.clearFile();
    }
    // Check for project, find the control
    Core::IVersionControl *projectControl = 0;
    if (const ProjectExplorer::Project *currentProject = pe->currentProject()) {
281
        state.currentProjectPath = currentProject->projectDirectory();
282
        state.currentProjectName = currentProject->displayName();
283
284
285
286
287
288
289
290
291
292
293
294
295
        projectControl = vcsManager->findVersionControlForDirectory(state.currentProjectPath,
                                                                    &state.currentProjectTopLevel);
        if (projectControl) {
            // If we have both, let the file's one take preference
            if (fileControl && projectControl != fileControl) {
                state.clearProject();
            }
        } else {
            state.clearProject(); // No control found
        }
    }
    // Assemble state and emit signal.
    Core::IVersionControl *vc = state.currentFile.isEmpty() ? projectControl : fileControl;
296
297
    if (!vc) // Need a repository to patch
        state.clearPatchFile();
298
    if (debug)
299
        qDebug() << state << (vc ? vc->displayName() : QString(QLatin1String("No version control")));
300
    emit stateChanged(state, vc);
con's avatar
con committed
301
}
302

303
304
305
306
307
308
309
} // namespace Internal

class VCSBasePluginStateData : public QSharedData {
public:
    Internal::State m_state;
};

310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
/*!
    \class  VCSBase::VCSBasePluginState

    \brief Relevant state information of the VCS plugins

    Qt Creator's state relevant to VCS plugins is a tuple of

    \list
    \o Current file and it's version system control/top level
    \o Current project and it's version system control/top level
    \endlist

    \sa VCSBase::VCSBasePlugin
*/

325
VCSBasePluginState::VCSBasePluginState() : data(new VCSBasePluginStateData)
con's avatar
con committed
326
327
328
{
}

329
VCSBasePluginState::VCSBasePluginState(const VCSBasePluginState &rhs) : data(rhs.data)
330
331
332
{
}

333
VCSBasePluginState &VCSBasePluginState::operator=(const VCSBasePluginState &rhs)
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
    if (this != &rhs)
        data.operator=(rhs.data);
    return *this;
}

VCSBasePluginState::~VCSBasePluginState()
{
}

QString VCSBasePluginState::currentFile() const
{
    return data->m_state.currentFile;
}

QString VCSBasePluginState::currentFileName() const
{
    return data->m_state.currentFileName;
}

QString VCSBasePluginState::currentFileTopLevel() const
{
    return data->m_state.currentFileTopLevel;
}

QString VCSBasePluginState::currentFileDirectory() const
{
    return data->m_state.currentFileDirectory;
}

QString VCSBasePluginState::relativeCurrentFile() const
{
    QTC_ASSERT(hasFile(), return QString())
    return QDir(data->m_state.currentFileTopLevel).relativeFilePath(data->m_state.currentFile);
}

370
371
372
373
374
375
376
377
378
379
QString VCSBasePluginState::currentPatchFile() const
{
    return data->m_state.currentPatchFile;
}

QString VCSBasePluginState::currentPatchFileDisplayName() const
{
    return data->m_state.currentPatchFileDisplayName;
}

380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
QString VCSBasePluginState::currentProjectPath() const
{
    return data->m_state.currentProjectPath;
}

QString VCSBasePluginState::currentProjectName() const
{
    return data->m_state.currentProjectName;
}

QString VCSBasePluginState::currentProjectTopLevel() const
{
    return data->m_state.currentProjectTopLevel;
}

QStringList VCSBasePluginState::relativeCurrentProject() const
{
    QStringList rc;
    QTC_ASSERT(hasProject(), return rc)
    if (data->m_state.currentProjectTopLevel != data->m_state.currentProjectPath)
        rc.append(QDir(data->m_state.currentProjectTopLevel).relativeFilePath(data->m_state.currentProjectPath));
    return rc;
402
403
}

404
bool VCSBasePluginState::hasTopLevel() const
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
    return data->m_state.hasFile() || data->m_state.hasProject();
}

QString VCSBasePluginState::topLevel() const
{
    return hasFile() ? data->m_state.currentFileTopLevel : data->m_state.currentProjectTopLevel;
}

bool VCSBasePluginState::equals(const Internal::State &rhs) const
{
    return data->m_state.equals(rhs);
}

bool VCSBasePluginState::equals(const VCSBasePluginState &rhs) const
{
    return equals(rhs.data->m_state);
}

void VCSBasePluginState::clear()
{
    data->m_state.clear();
}

void VCSBasePluginState::setState(const Internal::State &s)
{
    data->m_state = s;
}

bool VCSBasePluginState::isEmpty() const
{
    return data->m_state.isEmpty();
}

bool VCSBasePluginState::hasFile() const
{
    return data->m_state.hasFile();
}

444
445
446
447
448
bool VCSBasePluginState::hasPatchFile() const
{
    return !data->m_state.currentPatchFile.isEmpty();
}

449
450
451
452
453
454
455
456
457
458
459
bool VCSBasePluginState::hasProject() const
{
    return data->m_state.hasProject();
}

VCSBASE_EXPORT QDebug operator<<(QDebug in, const VCSBasePluginState &state)
{
    in << state.data->m_state;
    return in;
}

460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
/*!
    \class VCSBase::VCSBasePlugin

    \brief Base class for all version control plugins.

    The plugin connects to the
    relevant change signals in Qt Creator and calls the virtual
    updateActions() for the plugins to update their menu actions
    according to the new state. This is done centrally to avoid
    single plugins repeatedly invoking searches/QFileInfo on files,
    etc.

    Independently, there are accessors for current patch files, which return
    a file name if the current file could be a patch file which could be applied
    and a repository exists.

    If current file/project are managed
    by different version controls, the project is discarded and only
    the current file is taken into account, allowing to do a diff
    also when the project of a file is not opened.

    When triggering an action, a copy of the state should be made to
    keep it, as it may rapidly change due to context changes, etc.

    The class also detects the VCS plugin submit editor closing and calls
    the virtual submitEditorAboutToClose() to trigger the submit process.
*/

488
struct VCSBasePluginPrivate {
489
    explicit VCSBasePluginPrivate(const QString &submitEditorId);
490

491
492
    inline bool supportsRepositoryCreation() const;

493
    const QString m_submitEditorId;
494
495
496
    Core::IVersionControl *m_versionControl;
    VCSBasePluginState m_state;
    int m_actionState;
497
498
499
500
501
    QAction *m_testSnapshotAction;
    QAction *m_testListSnapshotsAction;
    QAction *m_testRestoreSnapshotAction;
    QAction *m_testRemoveSnapshotAction;
    QString m_testLastSnapshot;
502
503
504
505

    static Internal::StateListener *m_listener;
};

506
507
VCSBasePluginPrivate::VCSBasePluginPrivate(const QString &submitEditorId) :
    m_submitEditorId(submitEditorId),
508
    m_versionControl(0),
509
510
511
512
513
    m_actionState(-1),
    m_testSnapshotAction(0),
    m_testListSnapshotsAction(0),
    m_testRestoreSnapshotAction(0),
    m_testRemoveSnapshotAction(0)
514
515
516
{
}

517
518
519
520
521
bool VCSBasePluginPrivate::supportsRepositoryCreation() const
{
    return m_versionControl && m_versionControl->supportsOperation(Core::IVersionControl::CreateRepositoryOperation);
}

522
523
Internal::StateListener *VCSBasePluginPrivate::m_listener = 0;

524
525
VCSBasePlugin::VCSBasePlugin(const QString &submitEditorId) :
    d(new VCSBasePluginPrivate(submitEditorId))
526
527
528
529
530
531
532
533
{
}

VCSBasePlugin::~VCSBasePlugin()
{
    delete d;
}

534
void VCSBasePlugin::initializeVcs(Core::IVersionControl *vc)
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
{
    d->m_versionControl = vc;
    addAutoReleasedObject(vc);

    Internal::VCSPlugin *plugin = Internal::VCSPlugin::instance();
    connect(plugin->coreListener(), SIGNAL(submitEditorAboutToClose(VCSBaseSubmitEditor*,bool*)),
            this, SLOT(slotSubmitEditorAboutToClose(VCSBaseSubmitEditor*,bool*)));
    // First time: create new listener
    if (!VCSBasePluginPrivate::m_listener)
        VCSBasePluginPrivate::m_listener = new Internal::StateListener(plugin);
    connect(VCSBasePluginPrivate::m_listener,
            SIGNAL(stateChanged(VCSBase::Internal::State, Core::IVersionControl*)),
            this,
            SLOT(slotStateChanged(VCSBase::Internal::State,Core::IVersionControl*)));
}

551
552
553
554
555
556
void VCSBasePlugin::extensionsInitialized()
{
    // Initialize enable menus.
    VCSBasePluginPrivate::m_listener->slotStateChanged();
}

557
558
559
void VCSBasePlugin::slotSubmitEditorAboutToClose(VCSBaseSubmitEditor *submitEditor, bool *result)
{
    if (debug)
560
561
        qDebug() << this << d->m_submitEditorId << "Closing submit editor" << submitEditor << submitEditor->id();
    if (submitEditor->id() == d->m_submitEditorId)
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
        *result = submitEditorAboutToClose(submitEditor);
}

Core::IVersionControl *VCSBasePlugin::versionControl() const
{
    return d->m_versionControl;
}

void VCSBasePlugin::slotStateChanged(const VCSBase::Internal::State &newInternalState, Core::IVersionControl *vc)
{
    if (vc == d->m_versionControl) {
        // We are directly affected: Change state
        if (!d->m_state.equals(newInternalState)) {
            d->m_state.setState(newInternalState);
            updateActions(VCSEnabled);
577
        }
578
579
580
581
582
583
584
585
586
587
    } else {
        // Some other VCS plugin or state changed: Reset us to empty state.
        const ActionState newActionState = vc ? OtherVCSEnabled : NoVCSEnabled;
        if (d->m_actionState != newActionState || !d->m_state.isEmpty()) {
            d->m_actionState = newActionState;
            const VCSBasePluginState emptyState;
            d->m_state = emptyState;
            updateActions(newActionState);
        }
    }
588
589
}

590
const VCSBasePluginState &VCSBasePlugin::currentState() const
591
{
592
593
594
    return d->m_state;
}

595
bool VCSBasePlugin::enableMenuAction(ActionState as, QAction *menuAction) const
596
597
598
599
{
    if (debug)
        qDebug() << "enableMenuAction" << menuAction->text() << as;
    switch (as) {
600
601
    case VCSBase::VCSBasePlugin::NoVCSEnabled: {
        const bool supportsCreation = d->supportsRepositoryCreation();
602
        menuAction->setVisible(supportsCreation);
603
604
605
        menuAction->setEnabled(supportsCreation);
        return supportsCreation;
    }
606
607
608
609
610
611
612
613
614
    case VCSBase::VCSBasePlugin::OtherVCSEnabled:
        menuAction->setVisible(false);
        return false;
    case VCSBase::VCSBasePlugin::VCSEnabled:
        menuAction->setVisible(true);
        menuAction->setEnabled(true);
        break;
    }
    return true;
615
616
}

617
618
619
620
621
622
void VCSBasePlugin::promptToDeleteCurrentFile()
{
    const VCSBasePluginState state = currentState();
    QTC_ASSERT(state.hasFile(), return)
    const bool rc = Core::ICore::instance()->vcsManager()->promptToDelete(versionControl(), state.currentFile());
    if (!rc)
623
624
625
626
        QMessageBox::warning(0, tr("Version Control"),
                             tr("The file '%1' could not be deleted.").
                             arg(QDir::toNativeSeparators(state.currentFile())),
                             QMessageBox::Ok);
627
628
}

629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
static inline bool ask(QWidget *parent, const QString &title, const QString &question, bool defaultValue = true)

{
    const QMessageBox::StandardButton defaultButton = defaultValue ? QMessageBox::Yes : QMessageBox::No;
    return QMessageBox::question(parent, title, question, QMessageBox::Yes|QMessageBox::No, defaultButton) == QMessageBox::Yes;
}

void VCSBasePlugin::createRepository()
{
    QTC_ASSERT(d->m_versionControl->supportsOperation(Core::IVersionControl::CreateRepositoryOperation), return);
    // Find current starting directory
    QString directory;
    if (const ProjectExplorer::Project *currentProject = ProjectExplorer::ProjectExplorerPlugin::instance()->currentProject())
        directory = QFileInfo(currentProject->file()->fileName()).absolutePath();
    // Prompt for a directory that is not under version control yet
    QMainWindow *mw = Core::ICore::instance()->mainWindow();
    do {
646
        directory = QFileDialog::getExistingDirectory(mw, tr("Choose Repository Directory"), directory);
647
648
649
650
651
652
653
654
655
656
657
658
659
        if (directory.isEmpty())
            return;
        const Core::IVersionControl *managingControl = Core::ICore::instance()->vcsManager()->findVersionControlForDirectory(directory);
        if (managingControl == 0)
            break;
        const QString question = tr("The directory '%1' is already managed by a version control system (%2)."
                                    " Would you like to specify another directory?").arg(directory, managingControl->displayName());

        if (!ask(mw, tr("Repository already under version control"), question))
            return;
    } while (true);
    // Create
    const bool rc = d->m_versionControl->vcsCreateRepository(directory);
660
    const QString nativeDir = QDir::toNativeSeparators(directory);
661
    if (rc) {
Leena Miettinen's avatar
Leena Miettinen committed
662
        QMessageBox::information(mw, tr("Repository Created"),
663
664
                                 tr("A version control repository has been created in %1.").
                                 arg(nativeDir));
665
    } else {
Leena Miettinen's avatar
Leena Miettinen committed
666
        QMessageBox::warning(mw, tr("Repository Creation Failed"),
667
668
                                 tr("A version control repository could not be created in %1.").
                                 arg(nativeDir));
669
670
671
    }
}

672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
// For internal tests: Create actions driving IVersionControl's snapshot interface.
QList<QAction*> VCSBasePlugin::createSnapShotTestActions()
{
    if (!d->m_testSnapshotAction) {
        d->m_testSnapshotAction = new QAction(QLatin1String("Take snapshot"), this);
        connect(d->m_testSnapshotAction, SIGNAL(triggered()), this, SLOT(slotTestSnapshot()));
        d->m_testListSnapshotsAction = new QAction(QLatin1String("List snapshots"), this);
        connect(d->m_testListSnapshotsAction, SIGNAL(triggered()), this, SLOT(slotTestListSnapshots()));
        d->m_testRestoreSnapshotAction = new QAction(QLatin1String("Restore snapshot"), this);
        connect(d->m_testRestoreSnapshotAction, SIGNAL(triggered()), this, SLOT(slotTestRestoreSnapshot()));
        d->m_testRemoveSnapshotAction = new QAction(QLatin1String("Remove snapshot"), this);
        connect(d->m_testRemoveSnapshotAction, SIGNAL(triggered()), this, SLOT(slotTestRemoveSnapshot()));
    }
    QList<QAction*> rc;
    rc << d->m_testSnapshotAction << d->m_testListSnapshotsAction << d->m_testRestoreSnapshotAction
       << d->m_testRemoveSnapshotAction;
    return rc;
}

void VCSBasePlugin::slotTestSnapshot()
{
    QTC_ASSERT(currentState().hasTopLevel(), return)
    d->m_testLastSnapshot = versionControl()->vcsCreateSnapshot(currentState().topLevel());
    qDebug() << "Snapshot " << d->m_testLastSnapshot;
    VCSBaseOutputWindow::instance()->append(QLatin1String("Snapshot: ") + d->m_testLastSnapshot);
    if (!d->m_testLastSnapshot.isEmpty())
        d->m_testRestoreSnapshotAction->setText(QLatin1String("Restore snapshot ") + d->m_testLastSnapshot);
}

void VCSBasePlugin::slotTestListSnapshots()
{
    QTC_ASSERT(currentState().hasTopLevel(), return)
    const QStringList snapshots = versionControl()->vcsSnapshots(currentState().topLevel());
    qDebug() << "Snapshots " << snapshots;
    VCSBaseOutputWindow::instance()->append(QLatin1String("Snapshots: ") + snapshots.join(QLatin1String(", ")));
}

void VCSBasePlugin::slotTestRestoreSnapshot()
{
    QTC_ASSERT(currentState().hasTopLevel() && !d->m_testLastSnapshot.isEmpty(), return)
    const bool ok = versionControl()->vcsRestoreSnapshot(currentState().topLevel(), d->m_testLastSnapshot);
    const QString msg = d->m_testLastSnapshot+ (ok ? QLatin1String(" restored") : QLatin1String(" failed"));
    qDebug() << msg;
    VCSBaseOutputWindow::instance()->append(msg);
}

void VCSBasePlugin::slotTestRemoveSnapshot()
{
    QTC_ASSERT(currentState().hasTopLevel() && !d->m_testLastSnapshot.isEmpty(), return)
    const bool ok = versionControl()->vcsRemoveSnapshot(currentState().topLevel(), d->m_testLastSnapshot);
    const QString msg = d->m_testLastSnapshot+ (ok ? QLatin1String(" removed") : QLatin1String(" failed"));
    qDebug() << msg;
    VCSBaseOutputWindow::instance()->append(msg);
    d->m_testLastSnapshot.clear();
}

728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
// Find top level for version controls like git/Mercurial that have
// a directory at the top of the repository.
// Note that checking for the existence of files is preferred over directories
// since checking for directories can cause them to be created when
// AutoFS is used (due its automatically creating mountpoints when querying
// a directory). In addition, bail out when reaching the home directory
// of the user or root (generally avoid '/', where mountpoints are created).
QString VCSBasePlugin::findRepositoryForDirectory(const QString &dirS,
                                                  const QString &checkFile)
{
    if (debugRepositorySearch)
        qDebug() << ">VCSBasePlugin::findRepositoryForDirectory" << dirS << checkFile;
    QTC_ASSERT(!dirS.isEmpty() && !checkFile.isEmpty(), return QString());

    const QString root = QDir::rootPath();
    const QString home = QDir::homePath();

    QDir directory(dirS);
    do {
        const QString absDirPath = directory.absolutePath();
        if (absDirPath == root || absDirPath == home)
            break;

        if (QFileInfo(directory, checkFile).isFile()) {
            if (debugRepositorySearch)
                qDebug() << "<VCSBasePlugin::findRepositoryForDirectory> " << absDirPath;
            return absDirPath;
        }
    } while (directory.cdUp());
    if (debugRepositorySearch)
        qDebug() << "<VCSBasePlugin::findRepositoryForDirectory bailing out at " << directory.absolutePath();
    return QString();
}

762
763
764
765
766
767
768
769
770
771
772
// Is SSH prompt configured?
static inline QString sshPrompt()
{
    return VCSBase::Internal::VCSPlugin::instance()->settings().sshPasswordPrompt;
}

bool VCSBasePlugin::isSshPromptConfigured()
{
    return !sshPrompt().isEmpty();
}

773
void VCSBasePlugin::setProcessEnvironment(QProcessEnvironment *e, bool forceCLocale)
774
{
775
776
    if (forceCLocale)
        e->insert(QLatin1String("LANG"), QString(QLatin1Char('C')));
777
778
779
780
781
    const QString sshPromptBinary = sshPrompt();
    if (!sshPromptBinary.isEmpty())
        e->insert(QLatin1String("SSH_ASKPASS"), sshPromptBinary);
}

782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
// Run a process fully synchronously, returning Utils::SynchronousProcessResponse
// response struct and using the VCSBasePlugin flags as applicable
static Utils::SynchronousProcessResponse
    runVCS_FullySynchronously(const QString &workingDir,
                              const QString &binary,
                              const QStringList &arguments,
                              int timeOutMS,
                              QProcessEnvironment env,
                              unsigned flags,
                              QTextCodec *outputCodec = 0)
{
    VCSBase::VCSBaseOutputWindow *outputWindow = VCSBase::VCSBaseOutputWindow::instance();

    // Set up process
    unsigned processFlags = 0;
    if (VCSBasePlugin::isSshPromptConfigured() && (flags & VCSBasePlugin::SshPasswordPrompt))
        processFlags |= Utils::SynchronousProcess::UnixTerminalDisabled;
    QSharedPointer<QProcess> process = Utils::SynchronousProcess::createProcess(processFlags);
    if (!workingDir.isEmpty())
        process->setWorkingDirectory(workingDir);
    process->setProcessEnvironment(env);
    if (flags & VCSBasePlugin::MergeOutputChannels)
        process->setProcessChannelMode(QProcess::MergedChannels);

    // Start
807
808
    process->start(binary, arguments, QIODevice::ReadOnly);
    process->closeWriteChannel();
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
    Utils::SynchronousProcessResponse response;
    if (!process->waitForStarted()) {
        response.result = Utils::SynchronousProcessResponse::StartFailed;
        return response;
    }

    // process output
    QByteArray stdOut;
    QByteArray stdErr;
    const bool timedOut =
            !Utils::SynchronousProcess::readDataFromProcess(*process.data(), timeOutMS,
                                                            &stdOut, &stdErr, true);

    if (!stdErr.isEmpty()) {
        response.stdErr = QString::fromLocal8Bit(stdErr).remove('\r');
        if (!(flags & VCSBasePlugin::SuppressStdErrInLogWindow))
            outputWindow->append(response.stdErr);
    }

    if (!stdOut.isEmpty()) {
        response.stdOut = (outputCodec ? outputCodec->toUnicode(stdOut) : QString::fromLocal8Bit(stdOut))
                          .remove('\r');
        if (flags & VCSBasePlugin::ShowStdOutInLogWindow)
            outputWindow->append(response.stdOut);
    }

    // Result
    if (timedOut) {
        response.result = Utils::SynchronousProcessResponse::Hang;
    } else if (process->exitStatus() != QProcess::NormalExit) {
        response.result = Utils::SynchronousProcessResponse::TerminatedAbnormally;
    } else {
        response.result = process->exitCode() == 0 ?
                          Utils::SynchronousProcessResponse::Finished :
                          Utils::SynchronousProcessResponse::FinishedError;
    }
    return response;
}


849
Utils::SynchronousProcessResponse
850
851
852
853
854
855
VCSBasePlugin::runVCS(const QString &workingDir,
                      const QString &binary,
                      const QStringList &arguments,
                      int timeOutMS,
                      unsigned flags,
                      QTextCodec *outputCodec)
856
857
858
859
860
861
{
    const QProcessEnvironment env = QProcessEnvironment::systemEnvironment();
    return runVCS(workingDir, binary, arguments, timeOutMS, env,
                  flags, outputCodec);
}

862
863
864
865
866
867
868
Utils::SynchronousProcessResponse VCSBasePlugin::runVCS(const QString &workingDir,
                                                        const QString &binary,
                                                        const QStringList &arguments,
                                                        int timeOutMS,
                                                        QProcessEnvironment env,
                                                        unsigned flags,
                                                        QTextCodec *outputCodec)
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
{
    VCSBase::VCSBaseOutputWindow *outputWindow = VCSBase::VCSBaseOutputWindow::instance();

    if (!(flags & SuppressCommandLogging))
        outputWindow->appendCommand(workingDir, binary, arguments);

    const bool sshPromptConfigured = VCSBasePlugin::isSshPromptConfigured();
    if (debugExecution) {
        QDebug nsp = qDebug().nospace();
        nsp << "VCSBasePlugin::runVCS" << workingDir << binary << arguments
                << timeOutMS;
        if (flags & ShowStdOutInLogWindow)
            nsp << "stdout";
        if (flags & SuppressStdErrInLogWindow)
            nsp << "suppress_stderr";
        if (flags & SuppressFailMessageInLogWindow)
            nsp << "suppress_fail_msg";
        if (flags & MergeOutputChannels)
            nsp << "merge_channels";
        if (flags & SshPasswordPrompt)
            nsp << "ssh (" << sshPromptConfigured << ')';
        if (flags & SuppressCommandLogging)
            nsp << "suppress_log";
892
893
        if (flags & ForceCLocale)
            nsp << "c_locale";
894
895
        if (flags & FullySynchronously)
            nsp << "fully_synchronously";
896
897
898
899
        if (outputCodec)
            nsp << " Codec: " << outputCodec->name();
    }

900
    VCSBase::VCSBasePlugin::setProcessEnvironment(&env, (flags & ForceCLocale));
901
902
903
904
905
906

    Utils::SynchronousProcessResponse response;

    if (flags & FullySynchronously) {
        response = runVCS_FullySynchronously(workingDir, binary, arguments, timeOutMS,
                                             env, flags, outputCodec);
907
    } else {
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
        // Run, connect stderr to the output window
        Utils::SynchronousProcess process;
        if (!workingDir.isEmpty())
            process.setWorkingDirectory(workingDir);

        process.setProcessEnvironment(env);
        process.setTimeout(timeOutMS);
        if (outputCodec)
            process.setStdOutCodec(outputCodec);

        // Suppress terminal on UNIX for ssh prompts if it is configured.
        if (sshPromptConfigured && (flags & SshPasswordPrompt))
            process.setFlags(Utils::SynchronousProcess::UnixTerminalDisabled);

        // connect stderr to the output window if desired
        if (flags & MergeOutputChannels) {
            process.setProcessChannelMode(QProcess::MergedChannels);
        } else {
            if (!(flags & SuppressStdErrInLogWindow)) {
                process.setStdErrBufferedSignalsEnabled(true);
                connect(&process, SIGNAL(stdErrBuffered(QString,bool)), outputWindow, SLOT(append(QString)));
            }
930
931
        }

932
933
934
935
936
        // connect stdout to the output window if desired
        if (flags & ShowStdOutInLogWindow) {
            process.setStdOutBufferedSignalsEnabled(true);
            connect(&process, SIGNAL(stdOutBuffered(QString,bool)), outputWindow, SLOT(append(QString)));
        }
937

938
        process.setTimeOutMessageBoxEnabled(true);
939

940
941
942
        // Run!
        response = process.run(binary, arguments);
    }
943

944
    // Success/Fail message in appropriate window?
945
    if (response.result == Utils::SynchronousProcessResponse::Finished) {
946
        if (flags & ShowSuccessMessage)
947
            outputWindow->append(response.exitMessage(binary, timeOutMS));
948
949
    } else {
        if (!(flags & SuppressFailMessageInLogWindow))
950
            outputWindow->appendError(response.exitMessage(binary, timeOutMS));
951
    }
952

953
    return response;
954
}
955

956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
bool VCSBasePlugin::runFullySynchronous(const QString &workingDirectory,
                                        const QString &binary,
                                        const QStringList &arguments,
                                        const QProcessEnvironment &env,
                                        QByteArray* outputText,
                                        QByteArray* errorText,
                                        int timeoutMS,
                                        bool logCommandToWindow)
{
    VCSBase::VCSBaseOutputWindow *outputWindow = VCSBase::VCSBaseOutputWindow::instance();

    if (logCommandToWindow)
        outputWindow->appendCommand(workingDirectory, binary, arguments);

    QProcess process;
    process.setWorkingDirectory(workingDirectory);
    process.setProcessEnvironment(env);

    process.start(binary, arguments);
    process.closeWriteChannel();
    if (!process.waitForStarted()) {
        if (errorText) {
            const QString msg = QString::fromLatin1("Unable to execute '%1': %2:")
                                .arg(binary, process.errorString());
            *errorText = msg.toLocal8Bit();
        }
        return false;
    }

    if (!Utils::SynchronousProcess::readDataFromProcess(process, timeoutMS,
                                                        outputText, errorText, true)) {
        errorText->append(tr("Error: Executable timed out after %1s.").arg(timeoutMS / 1000).toLocal8Bit());
        Utils::SynchronousProcess::stopProcess(process);
        return false;
    }

    return process.exitStatus() == QProcess::NormalExit && process.exitCode() == 0;
}

995
996
997
998
999
1000
bool VCSBasePlugin::runPatch(const QByteArray &input, const QString &workingDirectory,
                             int strip, bool reverse)
{
    VCSBaseOutputWindow *ow = VCSBaseOutputWindow::instance();
    const QString patch = Internal::VCSPlugin::instance()->settings().patchCommand;
    if (patch.isEmpty()) {
1001
        ow->appendError(tr("There is no patch-command configured in the common 'Version Control' settings."));
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
        return false;
    }

    QProcess patchProcess;
    if (!workingDirectory.isEmpty())
        patchProcess.setWorkingDirectory(workingDirectory);
    QStringList args(QLatin1String("-p") + QString::number(strip));
    if (reverse)
        args << QLatin1String("-R");
    ow->appendCommand(QString(), patch, args);
    patchProcess.start(patch, args);
    if (!patchProcess.waitForStarted()) {
        ow->appendError(tr("Unable to launch '%1': %2").arg(patch, patchProcess.errorString()));
        return false;
    }
    patchProcess.write(input);
    patchProcess.closeWriteChannel();
    QByteArray stdOut;
    QByteArray stdErr;
    if (!Utils::SynchronousProcess::readDataFromProcess(patchProcess, 30000, &stdOut, &stdErr, true)) {
        Utils::SynchronousProcess::stopProcess(patchProcess);
        ow->appendError(tr("A timeout occurred running '%1'").arg(patch));
        return false;

    }
    if (!stdOut.isEmpty())
        ow->append(QString::fromLocal8Bit(stdOut));
    if (!stdErr.isEmpty())
        ow->append(QString::fromLocal8Bit(stdErr));

    if (patchProcess.exitStatus() != QProcess::NormalExit) {
        ow->appendError(tr("'%1' crashed.").arg(patch));
        return false;
    }
    if (patchProcess.exitCode() != 0) {
1037
        ow->appendError(tr("'%1' failed (exit code %2).").arg(patch).arg(patchProcess.exitCode()));
1038
1039
1040
1041
        return false;
    }
    return true;
}
con's avatar
con committed
1042
1043
} // namespace VCSBase

1044
#include "vcsbaseplugin.moc"