gerritplugin.cpp 20 KB
Newer Older
hjk's avatar
hjk committed
1
/****************************************************************************
2
**
3
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
hjk's avatar
hjk committed
4
** Contact: http://www.qt-project.org/legal
5
**
hjk's avatar
hjk committed
6
** This file is part of Qt Creator.
7
**
hjk's avatar
hjk committed
8
9
10
11
12
13
14
** 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 Digia.  For licensing terms and
** conditions see http://qt.digia.com/licensing.  For further information
** use the contact form at http://qt.digia.com/contact-us.
15
16
**
** GNU Lesser General Public License Usage
hjk's avatar
hjk committed
17
18
19
20
21
22
23
24
25
** Alternatively, 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.
**
** In addition, as a special exception, Digia gives you certain additional
** rights.  These rights are described in the Digia Qt LGPL Exception
26
27
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
hjk's avatar
hjk committed
28
****************************************************************************/
29
30
31
32
33
34

#include "gerritplugin.h"
#include "gerritparameters.h"
#include "gerritdialog.h"
#include "gerritmodel.h"
#include "gerritoptionspage.h"
35
#include "gerritpushdialog.h"
36

37
38
39
40
#include "../gitplugin.h"
#include "../gitclient.h"
#include "../gitversioncontrol.h"
#include "../gitconstants.h"
41
#include <vcsbase/vcsbaseconstants.h>
42
#include <vcsbase/vcsbaseeditor.h>
43
44
45
46
47
48
49
50
51
52
53

#include <coreplugin/icore.h>
#include <coreplugin/coreconstants.h>
#include <coreplugin/vcsmanager.h>
#include <coreplugin/progressmanager/progressmanager.h>
#include <coreplugin/progressmanager/futureprogress.h>
#include <coreplugin/documentmanager.h>
#include <coreplugin/actionmanager/actionmanager.h>
#include <coreplugin/actionmanager/actioncontainer.h>
#include <coreplugin/actionmanager/command.h>
#include <coreplugin/editormanager/editormanager.h>
54
#include <locator/commandlocator.h>
55
56
57
58
59
60
61
62
63
64

#include <vcsbase/vcsbaseoutputwindow.h>

#include <utils/synchronousprocess.h>

#include <QDebug>
#include <QProcess>
#include <QRegExp>
#include <QAction>
#include <QFileDialog>
65
#include <QMessageBox>
66
67
#include <QTemporaryFile>
#include <QDir>
68
#include <QMap>
69

70
71
using namespace Core;

72
73
74
75
76
enum { debug = 0 };

namespace Gerrit {
namespace Constants {
const char GERRIT_OPEN_VIEW[] = "Gerrit.OpenView";
77
const char GERRIT_PUSH[] = "Gerrit.Push";
78
79
80
81
82
83
}
namespace Internal {

enum FetchMode
{
    FetchDisplay,
84
    FetchCherryPick,
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
    FetchCheckout
};

/* FetchContext: Retrieves the patch and displays
 * or applies it as desired. Does deleteLater() once it is done. */

class FetchContext : public QObject
{
     Q_OBJECT
public:
    FetchContext(const QSharedPointer<GerritChange> &change,
                 const QString &repository, const QString &git,
                 const QSharedPointer<GerritParameters> &p,
                 FetchMode fm, QObject *parent = 0);
    ~FetchContext();

public slots:
    void start();

private slots:
    void processError(QProcess::ProcessError);
    void processFinished(int exitCode, QProcess::ExitStatus);
    void processReadyReadStandardError();
    void processReadyReadStandardOutput();

private:
    enum State
    {
113
        FetchState,
114
115
116
117
118
        DoneState,
        ErrorState
    };

    void handleError(const QString &message);
119
    void show();
120
    void cherryPick();
121
    void checkout();
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

    const QSharedPointer<GerritChange> m_change;
    const QString m_repository;
    const FetchMode m_fetchMode;
    const QString m_git;
    const QSharedPointer<GerritParameters> m_parameters;
    State m_state;
    QProcess m_process;
    QFutureInterface<void> m_progress;
};

FetchContext::FetchContext(const QSharedPointer<GerritChange> &change,
                           const QString &repository, const QString &git,
                           const QSharedPointer<GerritParameters> &p,
                           FetchMode fm, QObject *parent)
    : QObject(parent)
    , m_change(change)
    , m_repository(repository)
    , m_fetchMode(fm)
    , m_git(git)
    , m_parameters(p)
    , m_state(FetchState)
{
    connect(&m_process, SIGNAL(error(QProcess::ProcessError)),
            this, SLOT(processError(QProcess::ProcessError)));
    connect(&m_process, SIGNAL(finished(int,QProcess::ExitStatus)),
            this, SLOT(processFinished(int,QProcess::ExitStatus)));
    connect(&m_process, SIGNAL(readyReadStandardError()),
            this, SLOT(processReadyReadStandardError()));
    connect(&m_process, SIGNAL(readyReadStandardOutput()),
            this, SLOT(processReadyReadStandardOutput()));
    m_process.setWorkingDirectory(repository);
154
155
    m_process.setProcessEnvironment(Git::Internal::GitPlugin::instance()->
                                    gitClient()->processEnvironment());
156
    m_process.closeWriteChannel();
157
158
159
160
161
162
163
164
165
166
167
168
169
}

FetchContext::~FetchContext()
{
    if (m_progress.isRunning())
        m_progress.reportFinished();
    m_process.disconnect(this);
    Utils::SynchronousProcess::stopProcess(m_process);
}

void FetchContext::start()
{
    m_progress.setProgressRange(0, 2);
170
    FutureProgress *fp = ProgressManager::addTask(m_progress.future(), tr("Gerrit Fetch"),
171
                                           "gerrit-fetch");
172
    fp->setKeepOnFinish(FutureProgress::HideOnFinish);
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
    m_progress.reportStarted();
    // Order: initialize future before starting the process in case error handling is invoked.
    const QStringList args = m_change->gitFetchArguments(m_parameters);
    VcsBase::VcsBaseOutputWindow::instance()->appendCommand(m_repository, m_git, args);
    m_process.start(m_git, args);
    m_process.closeWriteChannel();
}

void FetchContext::processFinished(int exitCode, QProcess::ExitStatus es)
{
    if (es != QProcess::NormalExit) {
        handleError(tr("%1 crashed.").arg(m_git));
        return;
    }
    if (exitCode) {
        handleError(tr("%1 returned %2.").arg(m_git).arg(exitCode));
        return;
    }
191
    if (m_state == FetchState) {
192
        m_progress.setProgressValue(m_progress.progressValue() + 1);
193
194
195
196
197
198
199
200
201
202
        if (m_fetchMode == FetchDisplay)
            show();
        else if (m_fetchMode == FetchCherryPick)
            cherryPick();
        else if (m_fetchMode == FetchCheckout)
            checkout();

        m_progress.reportFinished();
        m_state = DoneState;
        deleteLater();
203
204
205
206
207
208
209
    }
}

void FetchContext::processReadyReadStandardError()
{
    // Note: fetch displays progress on stderr.
    const QString errorOutput = QString::fromLocal8Bit(m_process.readAllStandardError());
210
    if (m_state == FetchState)
211
        VcsBase::VcsBaseOutputWindow::instance()->append(errorOutput);
212
    else
213
214
215
216
217
218
        VcsBase::VcsBaseOutputWindow::instance()->appendError(errorOutput);
}

void FetchContext::processReadyReadStandardOutput()
{
    const QByteArray output = m_process.readAllStandardOutput();
219
    VcsBase::VcsBaseOutputWindow::instance()->append(QString::fromLocal8Bit(output));
220
221
222
223
224
225
226
227
228
229
230
231
232
233
}

void FetchContext::handleError(const QString &e)
{
    m_state = ErrorState;
    VcsBase::VcsBaseOutputWindow::instance()->appendError(e);
    m_progress.reportCanceled();
    m_progress.reportFinished();
    deleteLater();
}

void FetchContext::processError(QProcess::ProcessError e)
{
    const QString msg = tr("Error running %1: %2").arg(m_git, m_process.errorString());
234
    if (e == QProcess::FailedToStart)
235
        handleError(msg);
236
    else
237
238
239
        VcsBase::VcsBaseOutputWindow::instance()->appendError(msg);
}

240
void FetchContext::show()
241
{
242
243
244
245
    const QString title = QString::number(m_change->number) + QLatin1Char('/')
            + QString::number(m_change->currentPatchSet.patchSetNumber);
    Git::Internal::GitPlugin::instance()->gitClient()->show(
                m_repository, QLatin1String("FETCH_HEAD"), QStringList(), title);
246
247
}

248
void FetchContext::cherryPick()
249
{
250
    // Point user to errors.
251
252
    VcsBase::VcsBaseOutputWindow::instance()->popup(IOutputPane::ModeSwitch
                                                  | IOutputPane::WithFocus);
Petar Perisin's avatar
Petar Perisin committed
253
    Git::Internal::GitPlugin::instance()->gitClient()->synchronousCherryPick(
254
                m_repository, QLatin1String("FETCH_HEAD"));
255
256
}

257
258
259
260
261
262
263
void FetchContext::checkout()
{
    Git::Internal::GitPlugin::instance()->gitClient()->synchronousCheckout(
                m_repository, QLatin1String("FETCH_HEAD"));
}


264
265
266
267
268
269
270
271
272
273
GerritPlugin::GerritPlugin(QObject *parent)
    : QObject(parent)
    , m_parameters(new GerritParameters)
{
}

GerritPlugin::~GerritPlugin()
{
}

274
bool GerritPlugin::initialize(ActionContainer *ac)
275
{
276
    m_parameters->fromSettings(ICore::settings());
277
278
279

    QAction *openViewAction = new QAction(tr("Gerrit..."), this);

Andre Hartmann's avatar
Andre Hartmann committed
280
    m_gerritCommand =
281
282
        ActionManager::registerAction(openViewAction, Constants::GERRIT_OPEN_VIEW,
                           Context(Core::Constants::C_GLOBAL));
283
    connect(openViewAction, SIGNAL(triggered()), this, SLOT(openView()));
Andre Hartmann's avatar
Andre Hartmann committed
284
    ac->addAction(m_gerritCommand);
285

286
287
    QAction *pushAction = new QAction(tr("Push to Gerrit..."), this);

288
289
290
    Command *pushCommand =
        ActionManager::registerAction(pushAction, Constants::GERRIT_PUSH,
                           Context(Core::Constants::C_GLOBAL));
291
292
293
294
295
    connect(pushAction, SIGNAL(triggered()), this, SLOT(push()));
    ac->addAction(pushCommand);

    m_pushToGerritPair = ActionCommandPair(pushAction, pushCommand);

296
297
298
299
    Git::Internal::GitPlugin::instance()->addAutoReleasedObject(new GerritOptionsPage(m_parameters));
    return true;
}

300
301
302
303
304
305
306
void GerritPlugin::updateActions(bool hasTopLevel)
{
    m_pushToGerritPair.first->setEnabled(hasTopLevel);
}

void GerritPlugin::addToLocator(Locator::CommandLocator *locator)
{
Andre Hartmann's avatar
Andre Hartmann committed
307
    locator->appendCommand(m_gerritCommand);
308
309
310
    locator->appendCommand(m_pushToGerritPair.second);
}

311
void GerritPlugin::push(const QString &topLevel)
312
{
313
    // QScopedPointer is required to delete the dialog when leaving the function
314
    GerritPushDialog dialog(topLevel, m_reviewers, ICore::mainWindow());
315

316
    if (!dialog.localChangesFound())
317
318
        return;

Orgad Shaneh's avatar
Orgad Shaneh committed
319
    if (!dialog.valid()) {
320
        QMessageBox::warning(ICore::mainWindow(), tr("Initialization Failed"),
321
322
323
324
                              tr("Failed to initialize dialog. Aborting."));
        return;
    }

Orgad Shaneh's avatar
Orgad Shaneh committed
325
    if (dialog.exec() == QDialog::Rejected)
326
327
328
329
        return;

    QStringList args;

Orgad Shaneh's avatar
Orgad Shaneh committed
330
    m_reviewers = dialog.reviewers();
331
    const QStringList reviewers = m_reviewers.split(QLatin1Char(','),
332
333
334
335
336
337
338
339
340
341
342
                                                            QString::SkipEmptyParts);
    if (!reviewers.isEmpty()) {
        QString reviewersFlag(QLatin1String("--receive-pack=git receive-pack"));
        foreach (const QString &reviewer, reviewers) {
            const QString name = reviewer.trimmed();
            if (!name.isEmpty())
                reviewersFlag += QString::fromLatin1(" --reviewer=") + name;
        }
        args << reviewersFlag;
    }

Orgad Shaneh's avatar
Orgad Shaneh committed
343
344
    args << dialog.selectedRemoteName();
    QString target = dialog.selectedCommit();
345
346
    if (target.isEmpty())
        target = QLatin1String("HEAD");
Orgad Shaneh's avatar
Orgad Shaneh committed
347
348
349
    target += QLatin1String(":refs/") + dialog.selectedPushType() +
            QLatin1Char('/') + dialog.selectedRemoteBranchName();
    const QString topic = dialog.selectedTopic();
350
351
352
    if (!topic.isEmpty())
        target += QLatin1Char('/') + topic;
    args << target;
353

354
    Git::Internal::GitPlugin::instance()->gitClient()->push(topLevel, args);
355
356
}

357
358
359
360
361
// Open or raise the Gerrit dialog window.
void GerritPlugin::openView()
{
    if (m_dialog.isNull()) {
        while (!m_parameters->isValid()) {
362
363
            QMessageBox::warning(0, tr("Error"),
                    tr("Invalid Gerrit configuration. Host, user and ssh binary are mandatory."));
364
            const Id group = VcsBase::Constants::VCS_SETTINGS_CATEGORY;
365
            if (!ICore::showOptionsDialog(group, "Gerrit"))
366
367
                return;
        }
368
        GerritDialog *gd = new GerritDialog(m_parameters, ICore::mainWindow());
369
370
371
        gd->setModal(false);
        connect(gd, SIGNAL(fetchDisplay(QSharedPointer<Gerrit::Internal::GerritChange>)),
                this, SLOT(fetchDisplay(QSharedPointer<Gerrit::Internal::GerritChange>)));
372
373
        connect(gd, SIGNAL(fetchCherryPick(QSharedPointer<Gerrit::Internal::GerritChange>)),
                this, SLOT(fetchCherryPick(QSharedPointer<Gerrit::Internal::GerritChange>)));
374
375
        connect(gd, SIGNAL(fetchCheckout(QSharedPointer<Gerrit::Internal::GerritChange>)),
                this, SLOT(fetchCheckout(QSharedPointer<Gerrit::Internal::GerritChange>)));
376
377
378
        connect(this, SIGNAL(fetchStarted(QSharedPointer<Gerrit::Internal::GerritChange>)),
                gd, SLOT(fetchStarted(QSharedPointer<Gerrit::Internal::GerritChange>)));
        connect(this, SIGNAL(fetchFinished()), gd, SLOT(fetchFinished()));
379
380
381
382
383
384
385
386
387
        m_dialog = gd;
    }
    const Qt::WindowStates state = m_dialog.data()->windowState();
    if (state & Qt::WindowMinimized)
        m_dialog.data()->setWindowState(state & ~Qt::WindowMinimized);
    m_dialog.data()->show();
    m_dialog.data()->raise();
}

388
389
390
391
392
void GerritPlugin::push()
{
    push(Git::Internal::GitPlugin::instance()->currentState().topLevel());
}

393
394
395
396
397
QString GerritPlugin::gitBinary()
{
    bool ok;
    const QString git = Git::Internal::GitPlugin::instance()->gitClient()->gitBinaryPath(&ok);
    if (!ok) {
398
        VcsBase::VcsBaseOutputWindow::instance()->appendError(tr("Git is not available."));
399
400
401
402
403
404
405
406
407
        return QString();
    }
    return git;
}

// Find the branch of a repository.
QString GerritPlugin::branch(const QString &repository)
{
    Git::Internal::GitClient *client = Git::Internal::GitPlugin::instance()->gitClient();
408
    return client->synchronousCurrentLocalBranch(repository);
409
410
411
412
413
414
415
}

void GerritPlugin::fetchDisplay(const QSharedPointer<Gerrit::Internal::GerritChange> &change)
{
    fetch(change, FetchDisplay);
}

416
void GerritPlugin::fetchCherryPick(const QSharedPointer<Gerrit::Internal::GerritChange> &change)
417
{
418
    fetch(change, FetchCherryPick);
419
420
421
422
423
424
425
426
427
428
429
430
431
432
}

void GerritPlugin::fetchCheckout(const QSharedPointer<Gerrit::Internal::GerritChange> &change)
{
    fetch(change, FetchCheckout);
}

void GerritPlugin::fetch(const QSharedPointer<Gerrit::Internal::GerritChange> &change, int mode)
{
    // Locate git.
    const QString git = gitBinary();
    if (git.isEmpty())
        return;

433
434
435
436
437
438
439
440
    Git::Internal::GitClient* gitClient = Git::Internal::GitPlugin::instance()->gitClient();

    QString repository;
    bool verifiedRepository = false;
    if (!m_dialog.isNull() && !m_parameters.isNull() && !m_parameters->promptPath
            && QFile::exists(m_dialog->repositoryPath())) {
        repository = gitClient->findRepositoryForDirectory(m_dialog->repositoryPath());
    }
Petar Perisin's avatar
Petar Perisin committed
441

442
443
444
445
446
447
448
449
450
451
452
453
454
455
    if (!repository.isEmpty()) {
        // Check if remote from a working dir is the same as remote from patch
        QMap<QString, QString> remotesList = gitClient->synchronousRemotesList(repository);
        if (!remotesList.isEmpty()) {
            QStringList remotes = remotesList.values();
            foreach (QString remote, remotes) {
                if (remote.endsWith(QLatin1String(".git")))
                    remote.chop(4);
                if (remote.contains(m_parameters->host) && remote.endsWith(change->project)) {
                    verifiedRepository = true;
                    break;
                }
            }

456
457
458
459
            if (!verifiedRepository) {
                Git::Internal::SubmoduleDataMap submodules = gitClient->submoduleList(repository);
                foreach (const Git::Internal::SubmoduleData &submoduleData, submodules) {
                    QString remote = submoduleData.url;
460
461
462
                    if (remote.endsWith(QLatin1String(".git")))
                        remote.chop(4);
                    if (remote.contains(m_parameters->host) && remote.endsWith(change->project)
463
464
465
                            && QFile::exists(repository + QLatin1Char('/') + submoduleData.dir)) {
                        repository = QDir::cleanPath(repository + QLatin1Char('/')
                                                     + submoduleData.dir);
466
467
468
469
470
471
                        verifiedRepository = true;
                        break;
                    }
                }
            }

Petar Perisin's avatar
Petar Perisin committed
472
            if (!verifiedRepository) {
473
                QMessageBox::StandardButton answer = QMessageBox::question(
474
                            ICore::mainWindow(), tr("Remote Not Verified"),
475
                            tr("Change host %1\nand project %2\n\nwere not verified among remotes"
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
                               " in %3. Select different folder?")
                            .arg(m_parameters->host,
                                 change->project,
                                 QDir::toNativeSeparators(repository)),
                            QMessageBox::Yes | QMessageBox::No | QMessageBox::Cancel,
                            QMessageBox::Yes);
                switch (answer) {
                case QMessageBox::Cancel:
                    return;
                case QMessageBox::No:
                    verifiedRepository = true;
                    break;
                default:
                    break;
                }
            }
        }
    }

    if (!verifiedRepository) {
        // Ask the user for a repository to retrieve the change.
        const QString title =
                tr("Enter Local Repository for '%1' (%2)").arg(change->project, change->branch);
        const QString suggestedRespository =
                findLocalRepository(change->project, change->branch);
        repository = QFileDialog::getExistingDirectory(m_dialog.data(),
                                                       title, suggestedRespository);
    }

505
506
507
508
509
    if (repository.isEmpty())
        return;

    FetchContext *fc = new FetchContext(change, repository, git,
                                        m_parameters, FetchMode(mode), this);
510
511
    connect(fc, SIGNAL(destroyed(QObject*)), this, SIGNAL(fetchFinished()));
    emit fetchStarted(change);
512
513
514
515
516
517
    fc->start();
}

// Try to find a matching repository for a project by asking the VcsManager.
QString GerritPlugin::findLocalRepository(QString project, const QString &branch) const
{
hjk's avatar
hjk committed
518
    const QStringList gitRepositories = VcsManager::repositories(Git::Internal::GitPlugin::instance()->gitVersionControl());
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
    // Determine key (file name) to look for (qt/qtbase->'qtbase').
    const int slashPos = project.lastIndexOf(QLatin1Char('/'));
    if (slashPos != -1)
        project.remove(0, slashPos + 1);
    // When looking at branch 1.7, try to check folders
    // "qtbase_17", 'qtbase1.7' with a semi-smart regular expression.
    QScopedPointer<QRegExp> branchRegexp;
    if (!branch.isEmpty() && branch != QLatin1String("master")) {
        QString branchPattern = branch;
        branchPattern.replace(QLatin1String("."), QLatin1String("[\\.-_]?"));
        const QString pattern = QLatin1Char('^') + project
                                + QLatin1String("[-_]?")
                                + branchPattern + QLatin1Char('$');
        branchRegexp.reset(new QRegExp(pattern));
        if (!branchRegexp->isValid())
            branchRegexp.reset(); // Oops.
    }
    foreach (const QString &repository, gitRepositories) {
        const QString fileName = QFileInfo(repository).fileName();
        if ((!branchRegexp.isNull() && branchRegexp->exactMatch(fileName))
            || fileName == project) {
            // Perform a check on the branch.
            if (branch.isEmpty())  {
                return repository;
            } else {
                const QString repositoryBranch = GerritPlugin::branch(repository);
                if (repositoryBranch.isEmpty() || repositoryBranch == branch)
                    return repository;
            } // !branch.isEmpty()
        } // branchRegexp or file name match
    } // for repositories
    // No match, do we have  a projects folder?
    if (Core::DocumentManager::useProjectsDirectory())
552
        return DocumentManager::projectsDirectory();
553
554
555
556
557
558
559
560

    return QDir::currentPath();
}

} // namespace Internal
} // namespace Gerrit

#include "gerritplugin.moc"