gitclient.cpp 150 KB
Newer Older
hjk's avatar
hjk committed
1
/****************************************************************************
con's avatar
con committed
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
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 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
con's avatar
con committed
26 27
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
hjk's avatar
hjk committed
28
****************************************************************************/
hjk's avatar
hjk committed
29

con's avatar
con committed
30
#include "gitclient.h"
31
#include "gitutils.h"
hjk's avatar
hjk committed
32

con's avatar
con committed
33
#include "commitdata.h"
hjk's avatar
hjk committed
34 35
#include "gitconstants.h"
#include "gitplugin.h"
36
#include "gitsubmiteditor.h"
37
#include "gitversioncontrol.h"
38
#include "mergetool.h"
39
#include "branchadddialog.h"
Christian Kandeler's avatar
Christian Kandeler committed
40
#include "gerrit/gerritplugin.h"
con's avatar
con committed
41

42 43
#include <vcsbase/submitfilemodel.h>

con's avatar
con committed
44
#include <coreplugin/editormanager/editormanager.h>
hjk's avatar
hjk committed
45
#include <coreplugin/icore.h>
46
#include <coreplugin/vcsmanager.h>
47
#include <coreplugin/id.h>
48
#include <coreplugin/iversioncontrol.h>
49
#include <coreplugin/coreconstants.h>
50

51
#include <utils/hostosinfo.h>
hjk's avatar
hjk committed
52
#include <utils/qtcassert.h>
53
#include <utils/qtcprocess.h>
54
#include <utils/synchronousprocess.h>
55
#include <utils/fileutils.h>
Tobias Hunger's avatar
Tobias Hunger committed
56
#include <vcsbase/command.h>
hjk's avatar
hjk committed
57
#include <vcsbase/vcsbaseeditor.h>
58
#include <vcsbase/vcsbaseeditorparameterwidget.h>
59
#include <vcsbase/vcsbaseoutputwindow.h>
60
#include <vcsbase/vcsbaseplugin.h>
con's avatar
con committed
61

62
#include <diffeditor/diffeditor.h>
63
#include <diffeditor/diffshoweditor.h>
64 65
#include <diffeditor/diffeditorconstants.h>

66
#include <QCoreApplication>
67
#include <QDir>
68
#include <QFileInfo>
69
#include <QHash>
70
#include <QRegExp>
71
#include <QSignalMapper>
72
#include <QTime>
con's avatar
con committed
73

74
#include <QMessageBox>
75
#include <QPushButton>
76 77
#include <QToolButton>
#include <QTextCodec>
con's avatar
con committed
78

79
static const char GIT_DIRECTORY[] = ".git";
80
static const char graphLogFormatC[] = "%h %d %an %s %ci";
81
static const char HEAD[] = "HEAD";
82 83
static const char noColorOption[] = "--no-color";
static const char decorateOption[] = "--decorate";
con's avatar
con committed
84

85 86 87
namespace Git {
namespace Internal {

88 89 90 91 92 93
// Suppress git diff warnings about "LF will be replaced by CRLF..." on Windows.
static inline unsigned diffExecutionFlags()
{
    return Utils::HostOsInfo::isWindowsHost() ? unsigned(VcsBase::VcsBasePlugin::SuppressStdErrInLogWindow) : 0u;
}

94 95
using VcsBase::VcsBasePlugin;

96 97 98 99 100 101 102 103 104 105 106 107 108 109
class GitDiffSwitcher : public QObject
{
    Q_OBJECT

public:
    enum DiffType {
        DiffRepository,
        DiffFile,
        DiffFileList,
        DiffProjectList,
        DiffBranch,
        DiffShow
    };

110
    GitDiffSwitcher(Core::IEditor *parentEditor, GitClient *gitClient)
111
        : QObject(parentEditor),
112
          m_editor(parentEditor),
113
          m_gitClient(gitClient)
114
    {
115 116 117 118
        m_usingDiffEditor = gitClient->settings()->boolValue(GitSettings::useDiffEditorKey);
        QIcon actionIcon = m_usingDiffEditor
                ? QIcon(QLatin1String(Core::Constants::ICON_TEXT_DIFF))
                : QIcon(QLatin1String(Core::Constants::ICON_SIDE_BY_SIDE_DIFF));
119

120 121 122
        const QString actionToolTip = m_usingDiffEditor
                ? tr("Switch to Text Diff Editor")
                : tr("Switch to Side By Side Diff Editor");
123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146

        QAction *switchAction = new QAction(actionIcon, actionToolTip, parentEditor);
        parentEditor->toolBar()->addAction(switchAction);
        connect(switchAction, SIGNAL(triggered()), this, SLOT(execute()));
    }

    void setWorkingDirectory(const QString &workingDir) { m_workingDirectory = workingDir; }
    void setDiffType(DiffType type) { m_diffType = type; }
    void setFileName(const QString &fileName) { m_fileName = fileName; }
    void setFileList(const QStringList &stagedFiles, const QStringList &unstagedFiles)
    {
        m_stagedFiles = stagedFiles;
        m_unstagedFiles = unstagedFiles;
    }
    void setProjectList(const QStringList &projectFiles) { m_projectFiles = projectFiles; }
    void setBranchName(const QString &branchName) { m_branchName = branchName; }
    void setId(const QString &id) { m_id = id; }
    void setDisplayName(const QString &displayName) { m_displayName = displayName; }
    void setBaseArguments(const QStringList &args) { m_baseArguments = args; }

public slots:
    void execute();

private:
147
    Core::IEditor *m_editor;
148 149 150
    GitClient *m_gitClient;
    QString m_workingDirectory;
    DiffType m_diffType;
151
    bool m_usingDiffEditor;
152 153 154 155 156 157 158 159 160 161 162 163
    QString m_fileName;
    QStringList m_stagedFiles;
    QStringList m_unstagedFiles;
    QStringList m_projectFiles;
    QString m_branchName;
    QString m_id;
    QString m_displayName;
    QStringList m_baseArguments;
};

void GitDiffSwitcher::execute()
{
164
    m_gitClient->settings()->setValue(GitSettings::useDiffEditorKey, !m_usingDiffEditor);
165 166
    switch (m_diffType) {
    case DiffRepository:
167
        m_gitClient->diff(m_workingDirectory, QStringList(), QStringList());
168 169
        break;
    case DiffFile:
170
        m_gitClient->diff(m_workingDirectory, m_fileName);
171 172
        break;
    case DiffFileList:
173
        m_gitClient->diff(m_workingDirectory, m_unstagedFiles, m_stagedFiles);
174 175
        break;
    case DiffProjectList:
176
        m_gitClient->diff(m_workingDirectory, m_projectFiles, QStringList());
177 178
        break;
    case DiffBranch:
179
        m_gitClient->diffBranch(m_workingDirectory, m_baseArguments, m_branchName);
180 181
        break;
    case DiffShow:
182
        m_gitClient->show(m_fileName, m_id, m_baseArguments, m_displayName);
183 184 185 186
        break;
    default:
        break;
    }
187
    Core::EditorManager::closeEditor(m_editor, false);
188 189
}

190 191 192 193 194
class GitDiffHandler : public QObject
{
    Q_OBJECT

public:
195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216
    enum RevisionType {
        WorkingTree,
        Index,
        Other
    };

    struct Revision {
        Revision() : type(WorkingTree) { }
        Revision(RevisionType t) : type(t) { }
        Revision(RevisionType t, const QString &i) : type(t), id(i) { }
        RevisionType type;
        QString id; // can be sha or HEAD
        QString infoText() const
        {
            switch (type) {
            case WorkingTree: return tr("Working tree");
            case Index:       return tr("Index");
            default:          return id;
            }
        }
    };

217
    GitDiffHandler(DiffEditor::DiffEditor *editor,
jkobus's avatar
jkobus committed
218
                   const QString &gitPath,
219 220 221 222 223 224
                   const QString &workingDirectory,
                   const QProcessEnvironment &environment,
                   int timeout);

    // index -> working tree
    void diffFile(const QString &fileName);
225 226
    // stagedFileNames:   HEAD -> index
    // unstagedFileNames: index -> working tree
227 228 229 230 231
    void diffFiles(const QStringList &stagedFileNames, const QStringList &unstagedFileNames);
    // index -> working tree
    void diffProjects(const QStringList &projectPaths);
    // index -> working tree
    void diffRepository();
232 233 234 235
    // branch HEAD -> working tree
    void diffBranch(const QString &branchName);
    // id^ -> id
    void show(const QString &id);
236 237

private slots:
Orgad Shaneh's avatar
Orgad Shaneh committed
238 239 240
    void slotShowDescriptionReceived(const QString &data);
    void slotFileListReceived(const QString &fileList);
    void slotFileContentsReceived(const QString &contents);
241 242

private:
243
    void collectShowDescription(const QString &id);
244
    void collectFilesList(const QStringList &additionalArguments);
245
    void prepareForCollection();
246 247 248 249
    void collectFilesContents();
    void feedEditor();
    QString workingTreeContents(const QString &fileName) const;

250
    QPointer<DiffEditor::DiffEditor> m_editor;
251 252 253 254 255 256
    const QString m_gitPath;
    const QString m_workingDirectory;
    const QProcessEnvironment m_processEnvironment;
    const int m_timeout;
    const QString m_waitMessage;

257 258 259 260 261
    struct RevisionRange {
        RevisionRange() { }
        RevisionRange(const Revision &b, const Revision &e) : begin(b), end(e) { }
        Revision begin;
        Revision end;
262 263
    };

264 265 266 267 268 269
    // filename, revision range
    QMap<QString, QList<RevisionRange> > m_requestedRevisionRanges;
    // filename, revision, dummy
    QMap<QString, QMap<Revision, bool> > m_pendingRevisions;
    // filename, revision, contents
    QMap<QString, QMap<Revision, QString> > m_collectedRevisions;
270

271
    RevisionRange m_requestedRevisionRange;
272 273
};

274 275 276 277 278 279 280
inline bool operator<(const GitDiffHandler::Revision &rev1, const GitDiffHandler::Revision &rev2)
{
    if (rev1.type != rev2.type)
        return rev1.type < rev2.type;
    return rev1.id < rev2.id;
}

281
GitDiffHandler::GitDiffHandler(DiffEditor::DiffEditor *editor,
jkobus's avatar
jkobus committed
282
               const QString &gitPath,
283 284 285
               const QString &workingDirectory,
               const QProcessEnvironment &environment,
               int timeout)
jkobus's avatar
jkobus committed
286 287
    : m_editor(editor),
      m_gitPath(gitPath),
288 289 290 291 292 293 294 295 296
      m_workingDirectory(workingDirectory),
      m_processEnvironment(environment),
      m_timeout(timeout),
      m_waitMessage(tr("Waiting for data..."))
{
}

void GitDiffHandler::diffFile(const QString &fileName)
{
297
    m_requestedRevisionRange = RevisionRange(
298
                Revision(Index),
299 300 301
                Revision(WorkingTree));

    collectFilesList(QStringList() << QLatin1String("--") << fileName);
302 303 304 305
}

void GitDiffHandler::diffFiles(const QStringList &stagedFileNames, const QStringList &unstagedFileNames)
{
306 307
    RevisionRange stagedRange = RevisionRange(
                Revision(Other, QLatin1String(HEAD)),
308
                Revision(Index));
309 310 311
    RevisionRange unstagedRange = RevisionRange(
                Revision(Index),
                Revision(WorkingTree));
312

313 314 315 316 317 318 319
    for (int i = 0; i < stagedFileNames.count(); i++)
        m_requestedRevisionRanges[stagedFileNames.at(i)].append(stagedRange);

    for (int i = 0; i < unstagedFileNames.count(); i++)
        m_requestedRevisionRanges[unstagedFileNames.at(i)].append(unstagedRange);

    prepareForCollection();
320 321 322 323 324
    collectFilesContents();
}

void GitDiffHandler::diffProjects(const QStringList &projectPaths)
{
325
    m_requestedRevisionRange = RevisionRange(
326
                Revision(Index),
327 328
                Revision(WorkingTree));

329 330 331 332 333
    collectFilesList(QStringList() << QLatin1String("--") << projectPaths);
}

void GitDiffHandler::diffRepository()
{
334
    m_requestedRevisionRange = RevisionRange(
335
                Revision(Index),
336 337
                Revision(WorkingTree));

338 339 340
    collectFilesList(QStringList());
}

341 342 343 344 345 346 347 348 349 350 351 352 353 354 355
void GitDiffHandler::diffBranch(const QString &branchName)
{
    m_requestedRevisionRange = RevisionRange(
                Revision(Other, branchName),
                Revision(WorkingTree));

    collectFilesList(QStringList() << branchName);
}

void GitDiffHandler::show(const QString &id)
{
    Revision begin(Other, id + QLatin1Char('^'));
    Revision end(Other, id);
    m_requestedRevisionRange = RevisionRange(begin, end);

356 357 358 359 360
    collectShowDescription(id);
}

void GitDiffHandler::collectShowDescription(const QString &id)
{
Orgad Shaneh's avatar
Orgad Shaneh committed
361 362
    if (m_editor.isNull())
        return;
363 364
    m_editor->clear(m_waitMessage);
    VcsBase::Command *command = new VcsBase::Command(m_gitPath, m_workingDirectory, m_processEnvironment);
Orgad Shaneh's avatar
Orgad Shaneh committed
365
    command->setCodec(m_editor->editorWidget()->codec());
366
    connect(command, SIGNAL(output(QString)), this, SLOT(slotShowDescriptionReceived(QString)));
367
    QStringList arguments;
368
    arguments << QLatin1String("show") << QLatin1String("-s")
369
              << QLatin1String(noColorOption) << QLatin1String(decorateOption) << id;
370 371 372 373
    command->addJob(arguments, m_timeout);
    command->execute();
}

Orgad Shaneh's avatar
Orgad Shaneh committed
374
void GitDiffHandler::slotShowDescriptionReceived(const QString &description)
375
{
Orgad Shaneh's avatar
Orgad Shaneh committed
376 377
    if (m_editor.isNull())
        return;
378
    DiffEditor::DiffShowEditor *editor = qobject_cast<DiffEditor::DiffShowEditor *>(m_editor);
379 380 381 382
    if (editor) {
        editor->setDescription(GitPlugin::instance()->gitClient()->
                               extendedShowDescription(m_workingDirectory, description));
    }
383 384 385 386

    collectFilesList(QStringList()
                     << m_requestedRevisionRange.begin.id
                     << m_requestedRevisionRange.end.id);
387 388
}

389 390
void GitDiffHandler::collectFilesList(const QStringList &additionalArguments)
{
Orgad Shaneh's avatar
Orgad Shaneh committed
391 392
    if (m_editor.isNull())
        return;
jkobus's avatar
jkobus committed
393
    m_editor->clear(m_waitMessage);
394
    VcsBase::Command *command = new VcsBase::Command(m_gitPath, m_workingDirectory, m_processEnvironment);
Orgad Shaneh's avatar
Orgad Shaneh committed
395
    command->setCodec(m_editor->editorWidget()->codec());
396
    connect(command, SIGNAL(output(QString)), this, SLOT(slotFileListReceived(QString)));
397 398 399
    QStringList arguments;
    arguments << QLatin1String("diff") << QLatin1String("--name-only") << additionalArguments;
    command->addJob(arguments, m_timeout);
400
    command->addFlags(diffExecutionFlags());
401 402 403
    command->execute();
}

Orgad Shaneh's avatar
Orgad Shaneh committed
404
void GitDiffHandler::slotFileListReceived(const QString &fileList)
405 406 407 408
{
    if (m_editor.isNull())
        return;

409 410 411 412 413
    QStringList fileNames = fileList.split(QLatin1Char('\n'), QString::SkipEmptyParts);
    fileNames.removeDuplicates();

    for (int i = 0; i < fileNames.count(); i++)
        m_requestedRevisionRanges[fileNames.at(i)].append(m_requestedRevisionRange);
414

415
    prepareForCollection();
416 417 418
    collectFilesContents();
}

419
void GitDiffHandler::prepareForCollection()
420
{
421 422 423 424 425 426 427 428 429 430 431 432
    QMap<QString, QList<RevisionRange> >::const_iterator it
            = m_requestedRevisionRanges.constBegin();
    QMap<QString, QList<RevisionRange> >::const_iterator itEnd
            = m_requestedRevisionRanges.constEnd();
    while (it != itEnd) {
        const QString fileName = it.key();
        const QList<RevisionRange> &ranges = it.value();
        for (int i = 0; i < ranges.count(); i++) {
            const RevisionRange &range = ranges.at(i);
            m_pendingRevisions[fileName][range.begin] = false;
            m_pendingRevisions[fileName][range.end] = false;
        }
433

434 435 436
        ++it;
    }
}
437

438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462
void GitDiffHandler::collectFilesContents()
{
    QMap<QString, QMap<Revision, bool> >::iterator itFile
            = m_pendingRevisions.begin();
    QMap<QString, QMap<Revision, bool> >::iterator itFileEnd
            = m_pendingRevisions.end();
    while (itFile != itFileEnd) {
        const QString fileName = itFile.key();
        QMap<Revision, bool> &revisions = itFile.value();
        QMap<Revision, bool>::iterator itRev
                = revisions.begin();
        QMap<Revision, bool>::iterator itRevEnd
                = revisions.end();
        while (itRev != itRevEnd) {
            const Revision revision = itRev.key();
            if (revision.type == WorkingTree) {
                // collect file here

                m_collectedRevisions[fileName][revision] = workingTreeContents(fileName);

                itRev = revisions.erase(itRev); // iterate to the next revision
            } else {
                // prepare job here

                VcsBase::Command *command = new VcsBase::Command(m_gitPath, m_workingDirectory, m_processEnvironment);
Orgad Shaneh's avatar
Orgad Shaneh committed
463 464
                if (m_editor)
                    command->setCodec(m_editor->editorWidget()->codec());
465
                connect(command, SIGNAL(output(QString)), this, SLOT(slotFileContentsReceived(QString)));
466 467 468

                QString revisionArgument = (revision.type == Other)
                        ? revision.id : QString();
469
                revisionArgument += QLatin1Char(':');
470 471 472 473 474 475 476 477
                QStringList arguments;
                arguments << QLatin1String("show") << revisionArgument + fileName;
                command->addJob(arguments, m_timeout);
                command->execute();

                return;
            }
        }
478

479
        itFile = m_pendingRevisions.erase(itFile); // iterate to the next file
480
    }
481 482

    feedEditor();
483 484
}

Orgad Shaneh's avatar
Orgad Shaneh committed
485
void GitDiffHandler::slotFileContentsReceived(const QString &contents)
486 487 488 489
{
    if (m_editor.isNull())
        return;

490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508
    QMap<QString, QMap<Revision, bool> >::iterator itFile
            = m_pendingRevisions.begin();
    QMap<QString, QMap<Revision, bool> >::iterator itFileEnd
            = m_pendingRevisions.end();
    if (itFile != itFileEnd) {
        const QString fileName = itFile.key();
        QMap<Revision, bool> &revisions = itFile.value();
        QMap<Revision, bool>::iterator itRev
                = revisions.begin();
        QMap<Revision, bool>::iterator itRevEnd
                = revisions.end();
        if (itRev != itRevEnd) {
            m_collectedRevisions[fileName][itRev.key()] = contents;

            itRev = revisions.erase(itRev);
            if (revisions.isEmpty())
                m_pendingRevisions.erase(itFile);
        }
    }
509 510 511 512 513 514 515 516

    collectFilesContents();
}

void GitDiffHandler::feedEditor()
{
    QList<DiffEditor::DiffEditorWidget::DiffFilesContents> list;

517 518 519 520 521 522 523 524 525 526 527
    QMap<QString, QList<RevisionRange> >::const_iterator itFile
            = m_requestedRevisionRanges.constBegin();
    QMap<QString, QList<RevisionRange> >::const_iterator itFileEnd
            = m_requestedRevisionRanges.constEnd();
    while (itFile != itFileEnd) {
        const QString fileName = itFile.key();
        const QList<RevisionRange> &ranges = itFile.value();
        for (int i = 0; i < ranges.count(); i++) {
            const Revision leftRevision = ranges.at(i).begin;
            const Revision rightRevision = ranges.at(i).end;

528
            DiffEditor::DiffEditorWidget::DiffFilesContents dfc;
529 530 531 532
            dfc.leftFileInfo = DiffEditor::DiffEditorWidget::DiffFileInfo(fileName, leftRevision.infoText());
            dfc.leftText = m_collectedRevisions[fileName][leftRevision];
            dfc.rightFileInfo = DiffEditor::DiffEditorWidget::DiffFileInfo(fileName, rightRevision.infoText());
            dfc.rightText = m_collectedRevisions[fileName][rightRevision];
533 534
            list.append(dfc);
        }
535 536

        ++itFile;
537
    }
538

jkobus's avatar
jkobus committed
539
    m_editor->setDiff(list, m_workingDirectory);
540 541 542 543 544 545 546 547 548
    deleteLater();
}

QString GitDiffHandler::workingTreeContents(const QString &fileName) const
{
    QDir workingDir(m_workingDirectory);
    QString absoluteFileName = workingDir.absoluteFilePath(fileName);

    QFile file(absoluteFileName);
Orgad Shaneh's avatar
Orgad Shaneh committed
549
    if (file.open(QIODevice::ReadOnly | QIODevice::Text))
jkobus's avatar
jkobus committed
550
        return m_editor->editorWidget()->codec()->toUnicode(file.readAll());
551 552 553 554 555
    return QString();
}

///////////////////////////////////////////////////////////

hjk's avatar
hjk committed
556
class BaseGitDiffArgumentsWidget : public VcsBase::VcsBaseEditorParameterWidget
557
{
Friedemann Kleint's avatar
Friedemann Kleint committed
558
    Q_OBJECT
559

560
public:
561
    BaseGitDiffArgumentsWidget(GitClient *client, const QString &directory,
562
                               const QStringList &args) :
563
        m_workingDirectory(directory),
564
        m_client(client)
565
    {
566 567
        QTC_ASSERT(!directory.isEmpty(), return);
        QTC_ASSERT(m_client, return);
568

569 570 571
        m_patienceButton = addToggleButton(QLatin1String("--patience"), tr("Patience"),
                                           tr("Use the patience algorithm for calculating the differences."));
        mapSetting(m_patienceButton, client->settings()->boolPointer(GitSettings::diffPatienceKey));
572
        m_ignoreWSButton = addToggleButton(QLatin1String("--ignore-space-change"), tr("Ignore Whitespace"),
573 574
                                           tr("Ignore whitespace only changes."));
        mapSetting(m_ignoreWSButton, m_client->settings()->boolPointer(GitSettings::ignoreSpaceChangesInDiffKey));
575 576

        setBaseArguments(args);
577 578
    }

579
protected:
580 581
    QString m_workingDirectory;
    GitClient *m_client;
582 583
    QToolButton *m_patienceButton;
    QToolButton *m_ignoreWSButton;
584 585 586 587
};

class GitCommitDiffArgumentsWidget : public BaseGitDiffArgumentsWidget
{
Friedemann Kleint's avatar
Friedemann Kleint committed
588
    Q_OBJECT
589

590
public:
591
    GitCommitDiffArgumentsWidget(Git::Internal::GitClient *client, const QString &directory,
Orgad Shaneh's avatar
Orgad Shaneh committed
592
                                 const QStringList &unstaged, const QStringList &staged) :
593 594 595 596 597 598 599 600 601 602
        BaseGitDiffArgumentsWidget(client, directory, QStringList())
    {
        setFileNames(unstaged, staged);
    }

    void setFileNames(const QStringList &unstaged, const QStringList &staged)
    {
        m_unstagedFileNames = unstaged;
        m_stagedFileNames = staged;
    }
603

604
    void executeCommand()
605
    {
606
        m_client->diff(m_workingDirectory, m_unstagedFileNames, m_stagedFileNames);
607 608 609
    }

private:
610 611
    QStringList m_unstagedFileNames;
    QStringList m_stagedFileNames;
612 613 614 615
};

class GitFileDiffArgumentsWidget : public BaseGitDiffArgumentsWidget
{
Friedemann Kleint's avatar
Friedemann Kleint committed
616
    Q_OBJECT
617
public:
618
    GitFileDiffArgumentsWidget(Git::Internal::GitClient *client, const QString &directory,
Orgad Shaneh's avatar
Orgad Shaneh committed
619 620
                               const QString &file) :
        BaseGitDiffArgumentsWidget(client, directory, QStringList()),
621 622 623
        m_fileName(file)
    { }

624
    void executeCommand()
625
    {
626
        m_client->diff(m_workingDirectory, m_fileName);
627 628 629 630 631 632 633 634
    }

private:
    const QString m_fileName;
};

class GitBranchDiffArgumentsWidget : public BaseGitDiffArgumentsWidget
{
Friedemann Kleint's avatar
Friedemann Kleint committed
635
    Q_OBJECT
636
public:
637
    GitBranchDiffArgumentsWidget(Git::Internal::GitClient *client, const QString &directory,
638
                                 const QStringList &args, const QString &branch) :
639
        BaseGitDiffArgumentsWidget(client, directory, args),
640 641 642
        m_branchName(branch)
    { }

643
    void executeCommand()
644
    {
645
        m_client->diffBranch(m_workingDirectory, baseArguments(), m_branchName);
646 647 648 649 650 651
    }

private:
    const QString m_branchName;
};

Orgad Shaneh's avatar
Orgad Shaneh committed
652
class GitShowArgumentsWidget : public BaseGitDiffArgumentsWidget
653
{
Friedemann Kleint's avatar
Friedemann Kleint committed
654
    Q_OBJECT
655

656
public:
657
    GitShowArgumentsWidget(Git::Internal::GitClient *client,
658 659 660
                           const QString &directory,
                           const QStringList &args,
                           const QString &id) :
Orgad Shaneh's avatar
Orgad Shaneh committed
661
        BaseGitDiffArgumentsWidget(client, directory, args),
662 663
        m_client(client),
        m_workingDirectory(directory),
664 665
        m_id(id)
    {
666 667 668 669 670 671 672 673
        QList<ComboBoxItem> prettyChoices;
        prettyChoices << ComboBoxItem(tr("oneline"), QLatin1String("oneline"))
                      << ComboBoxItem(tr("short"), QLatin1String("short"))
                      << ComboBoxItem(tr("medium"), QLatin1String("medium"))
                      << ComboBoxItem(tr("full"), QLatin1String("full"))
                      << ComboBoxItem(tr("fuller"), QLatin1String("fuller"))
                      << ComboBoxItem(tr("email"), QLatin1String("email"))
                      << ComboBoxItem(tr("raw"), QLatin1String("raw"));
674
        mapSetting(addComboBox(QStringList(QLatin1String("--pretty=%1")), prettyChoices),
675
                   m_client->settings()->intPointer(GitSettings::showPrettyFormatKey));
676 677 678
    }

    void executeCommand()
679
    {
680
        m_client->show(m_workingDirectory, m_id, baseArguments());
681 682 683
    }

private:
684 685
    GitClient *m_client;
    QString m_workingDirectory;
686
    QString m_id;
687 688
};

hjk's avatar
hjk committed
689
class GitBlameArgumentsWidget : public VcsBase::VcsBaseEditorParameterWidget
690
{
Friedemann Kleint's avatar
Friedemann Kleint committed
691
    Q_OBJECT
692

693
public:
694 695 696 697
    GitBlameArgumentsWidget(Git::Internal::GitClient *client,
                            const QString &directory,
                            const QStringList &args,
                            const QString &revision, const QString &fileName) :
698
        m_editor(0),
699 700
        m_client(client),
        m_workingDirectory(directory),
701 702 703
        m_revision(revision),
        m_fileName(fileName)
    {
704 705 706
        mapSetting(addToggleButton(QString(), tr("Omit Date"),
                                   tr("Hide the date of a change from the output.")),
                   m_client->settings()->boolPointer(GitSettings::omitAnnotationDateKey));
707
        mapSetting(addToggleButton(QLatin1String("-w"), tr("Ignore Whitespace"),
708 709
                                   tr("Ignore whitespace only changes.")),
                   m_client->settings()->boolPointer(GitSettings::ignoreSpaceChangesInBlameKey));
710 711

        setBaseArguments(args);
712 713
    }

hjk's avatar
hjk committed
714
    void setEditor(VcsBase::VcsBaseEditorWidget *editor)
715
    {
716
        QTC_ASSERT(editor, return);
717 718 719
        m_editor = editor;
    }

720
    void executeCommand()
721
    {
722 723 724
        int line = -1;
        if (m_editor)
            line = m_editor->lineNumberOfCurrentEditor();
725
        m_client->blame(m_workingDirectory, baseArguments(), m_fileName, m_revision, line);
726 727 728
    }

private:
hjk's avatar
hjk committed
729
    VcsBase::VcsBaseEditorWidget *m_editor;
730 731
    GitClient *m_client;
    QString m_workingDirectory;
732 733 734 735
    QString m_revision;
    QString m_fileName;
};

736 737 738 739 740 741 742 743 744
class GitLogArgumentsWidget : public BaseGitDiffArgumentsWidget
{
    Q_OBJECT

public:
    GitLogArgumentsWidget(Git::Internal::GitClient *client,
                          const QString &directory,
                          bool enableAnnotationContextMenu,
                          const QStringList &args,
745
                          const QString &fileName) :
746 747 748
        BaseGitDiffArgumentsWidget(client, directory, args),
        m_client(client),
        m_workingDirectory(directory),
749
        m_enableAnnotationContextMenu(enableAnnotationContextMenu)
750
    {
Orgad Shaneh's avatar
Orgad Shaneh committed
751
        QTC_ASSERT(!directory.isEmpty(), return);
752
        QToolButton *diffButton = addToggleButton(QLatin1String("--patch"), tr("Show Diff"),
753
                                              tr("Show difference."));
754 755 756 757 758 759 760 761 762 763 764
        mapSetting(diffButton, m_client->settings()->boolPointer(GitSettings::logDiffKey));
        connect(diffButton, SIGNAL(toggled(bool)), m_patienceButton, SLOT(setVisible(bool)));
        connect(diffButton, SIGNAL(toggled(bool)), m_ignoreWSButton, SLOT(setVisible(bool)));
        m_patienceButton->setVisible(diffButton->isChecked());
        m_ignoreWSButton->setVisible(diffButton->isChecked());
        QStringList graphArguments(QLatin1String("--graph"));
        graphArguments << QLatin1String("--oneline") << QLatin1String("--topo-order");
        graphArguments << (QLatin1String("--pretty=format:") + QLatin1String(graphLogFormatC));
        QToolButton *graphButton = addToggleButton(graphArguments, tr("Graph"),
                                              tr("Show textual graph log."));
        mapSetting(graphButton, m_client->settings()->boolPointer(GitSettings::graphLogKey));
765
        setFileName(fileName);
766 767
    }

768
    void setFileName(const QString &fileNames)
769
    {
770
        m_fileName = fileNames;
771 772 773 774
    }

    void executeCommand()
    {
775
        m_client->log(m_workingDirectory, m_fileName, m_enableAnnotationContextMenu, baseArguments());
776 777 778 779 780 781
    }

private:
    GitClient *m_client;
    QString m_workingDirectory;
    bool m_enableAnnotationContextMenu;
782
    QString m_fileName;
783 784
};

Orgad Shaneh's avatar
Orgad Shaneh committed
785 786 787 788
class ConflictHandler : public QObject
{
    Q_OBJECT
public:
Orgad Shaneh's avatar
Orgad Shaneh committed
789
    ConflictHandler(VcsBase::Command *parentCommand,
Orgad Shaneh's avatar
Orgad Shaneh committed
790
                    const QString &workingDirectory,
791
                    const QString &command = QString())
Orgad Shaneh's avatar
Orgad Shaneh committed
792
        : QObject(parentCommand),
Orgad Shaneh's avatar
Orgad Shaneh committed
793 794 795
          m_workingDirectory(workingDirectory),
          m_command(command)
    {
Orgad Shaneh's avatar
Orgad Shaneh committed
796
        if (parentCommand) {
Orgad Shaneh's avatar
Orgad Shaneh committed
797
            parentCommand->addFlags(VcsBasePlugin::ExpectRepoChanges);
798
            connect(parentCommand, SIGNAL(output(QString)), this, SLOT(readStdOut(QString)));
Orgad Shaneh's avatar
Orgad Shaneh committed
799 800
            connect(parentCommand, SIGNAL(errorText(QString)), this, SLOT(readStdErr(QString)));
        }
Orgad Shaneh's avatar
Orgad Shaneh committed
801 802 803 804
    }

    ~ConflictHandler()
    {
805 806 807 808 809 810 811 812 813 814
        // If interactive rebase editor window is closed, plugin is terminated
        // but referenced here when the command ends
        if (GitPlugin *plugin = GitPlugin::instance()) {
            GitClient *client = plugin->gitClient();
            if (m_commit.isEmpty() && m_files.isEmpty()) {
                if (client->checkCommandInProgress(m_workingDirectory) == GitClient::NoCommand)
                    client->endStashScope(m_workingDirectory);
            } else {
                client->handleMergeConflicts(m_workingDirectory, m_commit, m_files, m_command);
            }
Orgad Shaneh's avatar
Orgad Shaneh committed
815
        }
Orgad Shaneh's avatar
Orgad Shaneh committed
816 817
    }

Orgad Shaneh's avatar
Orgad Shaneh committed
818 819
public slots:
    void readStdOut(const QString &data)
Orgad Shaneh's avatar
Orgad Shaneh committed
820 821
    {
        static QRegExp patchFailedRE(QLatin1String("Patch failed at ([^\\n]*)"));
822
        static QRegExp conflictedFilesRE(QLatin1String("Merge conflict in ([^\\n]*)"));
Orgad Shaneh's avatar
Orgad Shaneh committed
823 824
        if (patchFailedRE.indexIn(data) != -1)
            m_commit = patchFailedRE.cap(1);
825 826 827 828
        int fileIndex = -1;
        while ((fileIndex = conflictedFilesRE.indexIn(data, fileIndex + 1)) != -1) {
            m_files.append(conflictedFilesRE.cap(1));
        }
Orgad Shaneh's avatar
Orgad Shaneh committed
829 830 831 832 833 834 835 836 837 838 839 840
    }

    void readStdErr(const QString &data)
    {
        static QRegExp couldNotApplyRE(QLatin1String("[Cc]ould not (?:apply|revert) ([^\\n]*)"));
        if (couldNotApplyRE.indexIn(data) != -1)
            m_commit = couldNotApplyRE.cap(1);
    }
private:
    QString m_workingDirectory;
    QString m_command;
    QString m_commit;
841
    QStringList m_files;
Orgad Shaneh's avatar
Orgad Shaneh committed
842 843
};

844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863
class ProgressParser : public VcsBase::ProgressParser
{
public:
    ProgressParser() :
        m_progressExp(QLatin1String("\\((\\d+)/(\\d+)\\)")) // e.g. Rebasing (7/42)
    {
    }

protected:
    void parseProgress(const QString &text)
    {
        if (m_progressExp.lastIndexIn(text) != -1)
            setProgressAndMaximum(m_progressExp.cap(1).toInt(), m_progressExp.cap(2).toInt());
    }

private:
    QRegExp m_progressExp;
};


Orgad Shaneh's avatar
Orgad Shaneh committed
864

hjk's avatar
hjk committed
865
Core::IEditor *locateEditor(const char *property, const QString &entry)
con's avatar
con committed
866
{
867 868 869
    foreach (Core::IDocument *document, Core::EditorManager::documentModel()->openedDocuments())
        if (document->property(property).toString() == entry)
            return Core::EditorManager::documentModel()->editorsForDocument(document).first();
con's avatar
con committed
870 871 872
    return 0;
}

873 874 875
// Return converted command output, remove '\r' read on Windows
static inline QString commandOutputFromLocal8Bit(const QByteArray &a)
{
876
    return Utils::SynchronousProcess::normalizeNewlines(QString::fromLocal8Bit(a));
877 878 879 880 881 882 883 884 885 886 887 888 889 890
}

// Return converted command output split into lines
static inline QStringList commandOutputLinesFromLocal8Bit(const QByteArray &a)
{
    QString output = commandOutputFromLocal8Bit(a);
    const QChar newLine = QLatin1Char('\n');
    if (output.endsWith(newLine))
        output.truncate(output.size() - 1);
    if (output.isEmpty())
        return QStringList();
    return output.split(newLine);
}

hjk's avatar
hjk committed
891
static inline VcsBase::VcsBaseOutputWindow *outputWindow()
892
{
hjk's avatar
hjk committed
893
    return VcsBase::VcsBaseOutputWindow::instance();
894 895
}

896 897
static inline QString msgRepositoryNotFound(const QString &dir)
{
Tobias Hunger's avatar
Tobias Hunger committed
898
    return GitClient::tr("Cannot determine the repository for \"%1\".").arg(dir);
899 900 901 902
}

static inline QString msgParseFilesFailed()
{
Tobias Hunger's avatar
Tobias Hunger committed
903
    return  GitClient::tr("Cannot parse the file output.");
904 905
}

Friedemann Kleint's avatar
Friedemann Kleint committed
906 907 908 909 910
static inline QString msgCannotLaunch(const QString &binary)
{
    return GitClient::tr("Cannot launch \"%1\".").arg(QDir::toNativeSeparators(binary));
}

911 912
static inline QString currentDocumentPath()
{
913 914
    if (Core::IDocument *document= Core::EditorManager::currentDocument())
        return QFileInfo(document->filePath()).path();
915
    return QString();
916 917
}

Orgad Shaneh's avatar
Orgad Shaneh committed
918 919 920 921 922 923
static inline QStringList statusArguments()
{
    return QStringList() << QLatin1String("-c") << QLatin1String("color.status=false")
                         << QLatin1String("status");
}

924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942
static inline void msgCannotRun(const QString &message, QString *errorMessage)
{
    if (errorMessage)
        *errorMessage = message;
    else
        outputWindow()->appendError(message);
}

static inline void msgCannotRun(const QStringList &args, const QString &workingDirectory,
                                const QByteArray &error, QString *errorMessage)
{
    const QString message = GitClient::tr("Cannot run \"%1 %2\" in \"%2\": %3")
            .arg(QLatin1String("git ") + args.join(QLatin1String(" ")),
                 QDir::toNativeSeparators(workingDirectory),
                 commandOutputFromLocal8Bit(error));

    msgCannotRun(message, errorMessage);
}

943
// ---------------- GitClient
944 945 946

const char *GitClient::stashNamePrefix = "stash@{";

947 948
GitClient::GitClient(GitSettings *settings) :
    m_cachedGitVersion(0),
Tobias Hunger's avatar
Tobias Hunger committed
949
    m_msgWait(tr("Waiting for data...")),
950 951
    m_settings(settings),
    m_disableEditor(false)
con's avatar
con committed
952
{
953
    QTC_CHECK(settings);
hjk's avatar
hjk committed
954
    connect(Core::ICore::instance(), SIGNAL(saveSettingsRequested()), this, SLOT(saveSettings()));
955 956 957
    m_gitQtcEditor = QString::fromLatin1("\"%1\" -client -block -pid %2")
            .arg(QCoreApplication::applicationFilePath())
            .arg(QCoreApplication::applicationPid());
con's avatar
con committed
958 959 960 961 962 963 964 965
}

GitClient::~GitClient()
{
}

QString GitClient::findRepositoryForDirectory(const QString &dir)
{
966 967
    if (dir.isEmpty() || dir.endsWith(QLatin1String("/.git"))
            || dir.contains(QLatin1String("/.git/"))) {
968
        return QString();
969
    }
Orgad Shaneh's avatar
Orgad Shaneh committed
970
    QDir directory(dir);
971 972 973
    QString dotGit = QLatin1String(GIT_DIRECTORY);
    // QFileInfo is outside loop, because it is faster this way
    QFileInfo fileInfo;
Orgad Shaneh's avatar
Orgad Shaneh committed
974
    do {
975 976 977 978 979 980 981
        if (directory.exists(dotGit)) {
            fileInfo.setFile(directory, dotGit);
            if (fileInfo.isFile())
                return directory.absolutePath();
            else if (directory.exists(QLatin1String(".git/config")))
                return directory.absolutePath();
        }
Orgad Shaneh's avatar
Orgad Shaneh committed
982
    } while (!directory.isRoot() && directory.cdUp());
983
    return QString();