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"
con's avatar
con committed
39

40 41
#include <vcsbase/submitfilemodel.h>

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

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

60
#include <diffeditor/diffeditor.h>
61
#include <diffeditor/diffshoweditor.h>
62 63
#include <diffeditor/diffeditorconstants.h>

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

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

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

83 84 85
namespace Git {
namespace Internal {

86 87
using VcsBase::VcsBasePlugin;

88 89 90 91 92 93 94 95 96 97 98 99 100 101
class GitDiffSwitcher : public QObject
{
    Q_OBJECT

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

102
    GitDiffSwitcher(Core::IEditor *parentEditor, GitClient *gitClient)
103
        : QObject(parentEditor),
104
          m_editor(parentEditor),
105
          m_gitClient(gitClient)
106
    {
107 108 109 110
        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));
111

112 113 114
        const QString actionToolTip = m_usingDiffEditor
                ? tr("Switch to Text Diff Editor")
                : tr("Switch to Side By Side Diff Editor");
115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138

        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:
139
    Core::IEditor *m_editor;
140 141 142
    GitClient *m_gitClient;
    QString m_workingDirectory;
    DiffType m_diffType;
143
    bool m_usingDiffEditor;
144 145 146 147 148 149 150 151 152 153 154 155
    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()
{
156
    m_gitClient->settings()->setValue(GitSettings::useDiffEditorKey, !m_usingDiffEditor);
157 158
    switch (m_diffType) {
    case DiffRepository:
159
        m_gitClient->diff(m_workingDirectory, QStringList(), QStringList());
160 161
        break;
    case DiffFile:
162
        m_gitClient->diff(m_workingDirectory, m_fileName);
163 164
        break;
    case DiffFileList:
165
        m_gitClient->diff(m_workingDirectory, m_unstagedFiles, m_stagedFiles);
166 167
        break;
    case DiffProjectList:
168
        m_gitClient->diff(m_workingDirectory, m_projectFiles, QStringList());
169 170
        break;
    case DiffBranch:
171
        m_gitClient->diffBranch(m_workingDirectory, m_baseArguments, m_branchName);
172 173
        break;
    case DiffShow:
174
        m_gitClient->show(m_fileName, m_id, m_baseArguments, m_displayName);
175 176 177 178
        break;
    default:
        break;
    }
179
    Core::EditorManager::closeEditor(m_editor, false);
180 181
}

182 183 184 185 186
class GitDiffHandler : public QObject
{
    Q_OBJECT

public:
187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208
    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;
            }
        }
    };

209
    GitDiffHandler(DiffEditor::DiffEditor *editor,
jkobus's avatar
jkobus committed
210
                   const QString &gitPath,
211 212 213 214 215 216
                   const QString &workingDirectory,
                   const QProcessEnvironment &environment,
                   int timeout);

    // index -> working tree
    void diffFile(const QString &fileName);
217 218
    // stagedFileNames:   HEAD -> index
    // unstagedFileNames: index -> working tree
219 220 221 222 223
    void diffFiles(const QStringList &stagedFileNames, const QStringList &unstagedFileNames);
    // index -> working tree
    void diffProjects(const QStringList &projectPaths);
    // index -> working tree
    void diffRepository();
224 225 226 227
    // branch HEAD -> working tree
    void diffBranch(const QString &branchName);
    // id^ -> id
    void show(const QString &id);
228 229

private slots:
Orgad Shaneh's avatar
Orgad Shaneh committed
230 231 232
    void slotShowDescriptionReceived(const QString &data);
    void slotFileListReceived(const QString &fileList);
    void slotFileContentsReceived(const QString &contents);
233 234

private:
235
    void collectShowDescription(const QString &id);
236
    void collectFilesList(const QStringList &additionalArguments);
237
    void prepareForCollection();
238 239 240 241
    void collectFilesContents();
    void feedEditor();
    QString workingTreeContents(const QString &fileName) const;

242
    QPointer<DiffEditor::DiffEditor> m_editor;
243 244 245 246 247 248
    const QString m_gitPath;
    const QString m_workingDirectory;
    const QProcessEnvironment m_processEnvironment;
    const int m_timeout;
    const QString m_waitMessage;

249 250 251 252 253
    struct RevisionRange {
        RevisionRange() { }
        RevisionRange(const Revision &b, const Revision &e) : begin(b), end(e) { }
        Revision begin;
        Revision end;
254 255
    };

256 257 258 259 260 261
    // 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;
262

263
    RevisionRange m_requestedRevisionRange;
264 265
};

266 267 268 269 270 271 272
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;
}

273
GitDiffHandler::GitDiffHandler(DiffEditor::DiffEditor *editor,
jkobus's avatar
jkobus committed
274
               const QString &gitPath,
275 276 277
               const QString &workingDirectory,
               const QProcessEnvironment &environment,
               int timeout)
jkobus's avatar
jkobus committed
278 279
    : m_editor(editor),
      m_gitPath(gitPath),
280 281 282 283 284 285 286 287 288
      m_workingDirectory(workingDirectory),
      m_processEnvironment(environment),
      m_timeout(timeout),
      m_waitMessage(tr("Waiting for data..."))
{
}

void GitDiffHandler::diffFile(const QString &fileName)
{
289
    m_requestedRevisionRange = RevisionRange(
290
                Revision(Index),
291 292 293
                Revision(WorkingTree));

    collectFilesList(QStringList() << QLatin1String("--") << fileName);
294 295 296 297
}

void GitDiffHandler::diffFiles(const QStringList &stagedFileNames, const QStringList &unstagedFileNames)
{
298 299
    RevisionRange stagedRange = RevisionRange(
                Revision(Other, QLatin1String(HEAD)),
300
                Revision(Index));
301 302 303
    RevisionRange unstagedRange = RevisionRange(
                Revision(Index),
                Revision(WorkingTree));
304

305 306 307 308 309 310 311
    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();
312 313 314 315 316
    collectFilesContents();
}

void GitDiffHandler::diffProjects(const QStringList &projectPaths)
{
317
    m_requestedRevisionRange = RevisionRange(
318
                Revision(Index),
319 320
                Revision(WorkingTree));

321 322 323 324 325
    collectFilesList(QStringList() << QLatin1String("--") << projectPaths);
}

void GitDiffHandler::diffRepository()
{
326
    m_requestedRevisionRange = RevisionRange(
327
                Revision(Index),
328 329
                Revision(WorkingTree));

330 331 332
    collectFilesList(QStringList());
}

333 334 335 336 337 338 339 340 341 342 343 344 345 346 347
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);

348 349 350 351 352
    collectShowDescription(id);
}

void GitDiffHandler::collectShowDescription(const QString &id)
{
Orgad Shaneh's avatar
Orgad Shaneh committed
353 354
    if (m_editor.isNull())
        return;
355 356
    m_editor->clear(m_waitMessage);
    VcsBase::Command *command = new VcsBase::Command(m_gitPath, m_workingDirectory, m_processEnvironment);
Orgad Shaneh's avatar
Orgad Shaneh committed
357
    command->setCodec(m_editor->editorWidget()->codec());
358
    connect(command, SIGNAL(output(QString)), this, SLOT(slotShowDescriptionReceived(QString)));
359
    QStringList arguments;
360
    arguments << QLatin1String("show") << QLatin1String("-s")
361
              << QLatin1String(noColorOption) << QLatin1String(decorateOption) << id;
362 363 364 365
    command->addJob(arguments, m_timeout);
    command->execute();
}

Orgad Shaneh's avatar
Orgad Shaneh committed
366
void GitDiffHandler::slotShowDescriptionReceived(const QString &description)
367
{
Orgad Shaneh's avatar
Orgad Shaneh committed
368 369
    if (m_editor.isNull())
        return;
370
    DiffEditor::DiffShowEditor *editor = qobject_cast<DiffEditor::DiffShowEditor *>(m_editor);
371 372 373 374
    if (editor) {
        editor->setDescription(GitPlugin::instance()->gitClient()->
                               extendedShowDescription(m_workingDirectory, description));
    }
375 376 377 378

    collectFilesList(QStringList()
                     << m_requestedRevisionRange.begin.id
                     << m_requestedRevisionRange.end.id);
379 380
}

381 382
void GitDiffHandler::collectFilesList(const QStringList &additionalArguments)
{
Orgad Shaneh's avatar
Orgad Shaneh committed
383 384
    if (m_editor.isNull())
        return;
jkobus's avatar
jkobus committed
385
    m_editor->clear(m_waitMessage);
386
    VcsBase::Command *command = new VcsBase::Command(m_gitPath, m_workingDirectory, m_processEnvironment);
Orgad Shaneh's avatar
Orgad Shaneh committed
387
    command->setCodec(m_editor->editorWidget()->codec());
388
    connect(command, SIGNAL(output(QString)), this, SLOT(slotFileListReceived(QString)));
389 390 391 392 393 394
    QStringList arguments;
    arguments << QLatin1String("diff") << QLatin1String("--name-only") << additionalArguments;
    command->addJob(arguments, m_timeout);
    command->execute();
}

Orgad Shaneh's avatar
Orgad Shaneh committed
395
void GitDiffHandler::slotFileListReceived(const QString &fileList)
396 397 398 399
{
    if (m_editor.isNull())
        return;

400 401 402 403 404
    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);
405

406
    prepareForCollection();
407 408 409
    collectFilesContents();
}

410
void GitDiffHandler::prepareForCollection()
411
{
412 413 414 415 416 417 418 419 420 421 422 423
    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;
        }
424

425 426 427
        ++it;
    }
}
428

429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453
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
454 455
                if (m_editor)
                    command->setCodec(m_editor->editorWidget()->codec());
456
                connect(command, SIGNAL(output(QString)), this, SLOT(slotFileContentsReceived(QString)));
457 458 459

                QString revisionArgument = (revision.type == Other)
                        ? revision.id : QString();
460
                revisionArgument += QLatin1Char(':');
461 462 463 464 465 466 467 468
                QStringList arguments;
                arguments << QLatin1String("show") << revisionArgument + fileName;
                command->addJob(arguments, m_timeout);
                command->execute();

                return;
            }
        }
469

470
        itFile = m_pendingRevisions.erase(itFile); // iterate to the next file
471
    }
472 473

    feedEditor();
474 475
}

Orgad Shaneh's avatar
Orgad Shaneh committed
476
void GitDiffHandler::slotFileContentsReceived(const QString &contents)
477 478 479 480
{
    if (m_editor.isNull())
        return;

481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499
    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);
        }
    }
500 501 502 503 504 505 506 507

    collectFilesContents();
}

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

508 509 510 511 512 513 514 515 516 517 518
    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;

519
            DiffEditor::DiffEditorWidget::DiffFilesContents dfc;
520 521 522 523
            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];
524 525
            list.append(dfc);
        }
526 527

        ++itFile;
528
    }
529

jkobus's avatar
jkobus committed
530
    m_editor->setDiff(list, m_workingDirectory);
531 532 533 534 535 536 537 538 539 540
    deleteLater();
}

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

    QFile file(absoluteFileName);
    if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {
jkobus's avatar
jkobus committed
541
        return m_editor->editorWidget()->codec()->toUnicode(file.readAll());
542 543 544 545 546 547
    }
    return QString();
}

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

hjk's avatar
hjk committed
548
class BaseGitDiffArgumentsWidget : public VcsBase::VcsBaseEditorParameterWidget
549
{
Friedemann Kleint's avatar
Friedemann Kleint committed
550
    Q_OBJECT
551

552
public:
553
    BaseGitDiffArgumentsWidget(GitClient *client, const QString &directory,
554
                               const QStringList &args) :
555
        m_workingDirectory(directory),
556
        m_client(client)
557
    {
558 559
        QTC_ASSERT(!directory.isEmpty(), return);
        QTC_ASSERT(m_client, return);
560

561 562 563
        m_patienceButton = addToggleButton(QLatin1String("--patience"), tr("Patience"),
                                           tr("Use the patience algorithm for calculating the differences."));
        mapSetting(m_patienceButton, client->settings()->boolPointer(GitSettings::diffPatienceKey));
564
        m_ignoreWSButton = addToggleButton(QLatin1String("--ignore-space-change"), tr("Ignore Whitespace"),
565 566
                                           tr("Ignore whitespace only changes."));
        mapSetting(m_ignoreWSButton, m_client->settings()->boolPointer(GitSettings::ignoreSpaceChangesInDiffKey));
567 568

        setBaseArguments(args);
569 570
    }

571
protected:
572 573
    QString m_workingDirectory;
    GitClient *m_client;
574 575
    QToolButton *m_patienceButton;
    QToolButton *m_ignoreWSButton;
576 577 578 579
};

class GitCommitDiffArgumentsWidget : public BaseGitDiffArgumentsWidget
{
Friedemann Kleint's avatar
Friedemann Kleint committed
580
    Q_OBJECT
581

582
public:
583
    GitCommitDiffArgumentsWidget(Git::Internal::GitClient *client, const QString &directory,
Orgad Shaneh's avatar
Orgad Shaneh committed
584
                                 const QStringList &unstaged, const QStringList &staged) :
585 586 587 588 589 590 591 592 593 594
        BaseGitDiffArgumentsWidget(client, directory, QStringList())
    {
        setFileNames(unstaged, staged);
    }

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

596
    void executeCommand()
597
    {
598
        m_client->diff(m_workingDirectory, m_unstagedFileNames, m_stagedFileNames);
599 600 601
    }

private:
602 603
    QStringList m_unstagedFileNames;
    QStringList m_stagedFileNames;
604 605 606 607
};

class GitFileDiffArgumentsWidget : public BaseGitDiffArgumentsWidget
{
Friedemann Kleint's avatar
Friedemann Kleint committed
608
    Q_OBJECT
609
public:
610
    GitFileDiffArgumentsWidget(Git::Internal::GitClient *client, const QString &directory,
Orgad Shaneh's avatar
Orgad Shaneh committed
611 612
                               const QString &file) :
        BaseGitDiffArgumentsWidget(client, directory, QStringList()),
613 614 615
        m_fileName(file)
    { }

616
    void executeCommand()
617
    {
618
        m_client->diff(m_workingDirectory, m_fileName);
619 620 621 622 623 624 625 626
    }

private:
    const QString m_fileName;
};

class GitBranchDiffArgumentsWidget : public BaseGitDiffArgumentsWidget
{
Friedemann Kleint's avatar
Friedemann Kleint committed
627
    Q_OBJECT
628
public:
629
    GitBranchDiffArgumentsWidget(Git::Internal::GitClient *client, const QString &directory,
630
                                 const QStringList &args, const QString &branch) :
631
        BaseGitDiffArgumentsWidget(client, directory, args),
632 633 634
        m_branchName(branch)
    { }

635
    void executeCommand()
636
    {
637
        m_client->diffBranch(m_workingDirectory, baseArguments(), m_branchName);
638 639 640 641 642 643
    }

private:
    const QString m_branchName;
};

Orgad Shaneh's avatar
Orgad Shaneh committed
644
class GitShowArgumentsWidget : public BaseGitDiffArgumentsWidget
645
{
Friedemann Kleint's avatar
Friedemann Kleint committed
646
    Q_OBJECT
647

648
public:
649
    GitShowArgumentsWidget(Git::Internal::GitClient *client,
650 651 652
                           const QString &directory,
                           const QStringList &args,
                           const QString &id) :
Orgad Shaneh's avatar
Orgad Shaneh committed
653
        BaseGitDiffArgumentsWidget(client, directory, args),
654 655
        m_client(client),
        m_workingDirectory(directory),
656 657
        m_id(id)
    {
658 659 660 661 662 663 664 665
        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"));
666
        mapSetting(addComboBox(QStringList(QLatin1String("--pretty=%1")), prettyChoices),
667
                   m_client->settings()->intPointer(GitSettings::showPrettyFormatKey));
668 669 670
    }

    void executeCommand()
671
    {
672
        m_client->show(m_workingDirectory, m_id, baseArguments());
673 674 675
    }

private:
676 677
    GitClient *m_client;
    QString m_workingDirectory;
678
    QString m_id;
679 680
};

hjk's avatar
hjk committed
681
class GitBlameArgumentsWidget : public VcsBase::VcsBaseEditorParameterWidget
682
{
Friedemann Kleint's avatar
Friedemann Kleint committed
683
    Q_OBJECT
684

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

        setBaseArguments(args);
704 705
    }

hjk's avatar
hjk committed
706
    void setEditor(VcsBase::VcsBaseEditorWidget *editor)
707
    {
708
        QTC_ASSERT(editor, return);
709 710 711
        m_editor = editor;
    }

712
    void executeCommand()
713
    {
714 715 716
        int line = -1;
        if (m_editor)
            line = m_editor->lineNumberOfCurrentEditor();
717
        m_client->blame(m_workingDirectory, baseArguments(), m_fileName, m_revision, line);
718 719 720
    }

private:
hjk's avatar
hjk committed
721
    VcsBase::VcsBaseEditorWidget *m_editor;
722 723
    GitClient *m_client;
    QString m_workingDirectory;
724 725 726 727
    QString m_revision;
    QString m_fileName;
};

728 729 730 731 732 733 734 735 736
class GitLogArgumentsWidget : public BaseGitDiffArgumentsWidget
{
    Q_OBJECT

public:
    GitLogArgumentsWidget(Git::Internal::GitClient *client,
                          const QString &directory,
                          bool enableAnnotationContextMenu,
                          const QStringList &args,
737
                          const QString &fileName) :
738 739 740
        BaseGitDiffArgumentsWidget(client, directory, args),
        m_client(client),
        m_workingDirectory(directory),
741
        m_enableAnnotationContextMenu(enableAnnotationContextMenu)
742
    {
Orgad Shaneh's avatar
Orgad Shaneh committed
743
        QTC_ASSERT(!directory.isEmpty(), return);
744
        QToolButton *diffButton = addToggleButton(QLatin1String("--patch"), tr("Show Diff"),
745
                                              tr("Show difference."));
746 747 748 749 750 751 752 753 754 755 756
        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));
757
        setFileName(fileName);
758 759
    }

760
    void setFileName(const QString &fileNames)
761
    {
762
        m_fileName = fileNames;
763 764 765 766
    }

    void executeCommand()
    {
767
        m_client->log(m_workingDirectory, m_fileName, m_enableAnnotationContextMenu, baseArguments());
768 769 770 771 772 773
    }

private:
    GitClient *m_client;
    QString m_workingDirectory;
    bool m_enableAnnotationContextMenu;
774
    QString m_fileName;
775 776
};

Orgad Shaneh's avatar
Orgad Shaneh committed
777 778 779 780
class ConflictHandler : public QObject
{
    Q_OBJECT
public:
Orgad Shaneh's avatar
Orgad Shaneh committed
781
    ConflictHandler(VcsBase::Command *parentCommand,
Orgad Shaneh's avatar
Orgad Shaneh committed
782
                    const QString &workingDirectory,
783
                    const QString &command = QString())
Orgad Shaneh's avatar
Orgad Shaneh committed
784
        : QObject(parentCommand),
Orgad Shaneh's avatar
Orgad Shaneh committed
785 786 787
          m_workingDirectory(workingDirectory),
          m_command(command)
    {
Orgad Shaneh's avatar
Orgad Shaneh committed
788
        if (parentCommand) {
Orgad Shaneh's avatar
Orgad Shaneh committed
789
            parentCommand->addFlags(VcsBasePlugin::ExpectRepoChanges);
790
            connect(parentCommand, SIGNAL(output(QString)), this, SLOT(readStdOut(QString)));
Orgad Shaneh's avatar
Orgad Shaneh committed
791 792
            connect(parentCommand, SIGNAL(errorText(QString)), this, SLOT(readStdErr(QString)));
        }
Orgad Shaneh's avatar
Orgad Shaneh committed
793 794 795 796
    }

    ~ConflictHandler()
    {
797 798 799 800 801 802 803 804 805 806
        // 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
807
        }
Orgad Shaneh's avatar
Orgad Shaneh committed
808 809
    }

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

    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;
833
    QStringList m_files;
Orgad Shaneh's avatar
Orgad Shaneh committed
834 835
};

836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855
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
856

hjk's avatar
hjk committed
857
Core::IEditor *locateEditor(const char *property, const QString &entry)
con's avatar
con committed
858
{
859 860 861
    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
862 863 864
    return 0;
}

865 866 867
// Return converted command output, remove '\r' read on Windows
static inline QString commandOutputFromLocal8Bit(const QByteArray &a)
{
868
    return Utils::SynchronousProcess::normalizeNewlines(QString::fromLocal8Bit(a));
869 870 871 872 873 874 875 876 877 878 879 880 881 882
}

// 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
883
static inline VcsBase::VcsBaseOutputWindow *outputWindow()
884
{
hjk's avatar
hjk committed
885
    return VcsBase::VcsBaseOutputWindow::instance();
886 887
}

888 889
static inline QString msgRepositoryNotFound(const QString &dir)
{
Tobias Hunger's avatar
Tobias Hunger committed
890
    return GitClient::tr("Cannot determine the repository for \"%1\".").arg(dir);
891 892 893 894
}

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

Friedemann Kleint's avatar
Friedemann Kleint committed
898 899 900 901 902
static inline QString msgCannotLaunch(const QString &binary)
{
    return GitClient::tr("Cannot launch \"%1\".").arg(QDir::toNativeSeparators(binary));
}

903 904
static inline QString currentDocumentPath()
{
905 906
    if (Core::IDocument *document= Core::EditorManager::currentDocument())
        return QFileInfo(document->filePath()).path();
907
    return QString();
908 909
}

Orgad Shaneh's avatar