gitclient.cpp 147 KB
Newer Older
hjk's avatar
hjk committed
1
/****************************************************************************
con's avatar
con committed
2
**
3
** Copyright (C) 2014 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
88
89
90
91
// 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;
}

92
93
using VcsBase::VcsBasePlugin;

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

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

108
    GitDiffSwitcher(Core::IEditor *parentEditor, GitClient *gitClient)
109
        : QObject(parentEditor),
110
          m_editor(parentEditor),
111
          m_gitClient(gitClient)
112
    {
113
114
115
116
        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));
117

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

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

188
189
190
191
192
class GitDiffHandler : public QObject
{
    Q_OBJECT

public:
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
    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;
            }
        }
    };

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

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

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

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

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

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

262
263
264
265
266
267
    // 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;
268

269
    RevisionRange m_requestedRevisionRange;
270
271
};

272
273
274
275
276
277
278
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;
}

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

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

    collectFilesList(QStringList() << QLatin1String("--") << fileName);
300
301
302
303
}

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

311
312
313
314
315
316
317
    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();
318
319
320
321
322
    collectFilesContents();
}

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

327
328
329
330
331
    collectFilesList(QStringList() << QLatin1String("--") << projectPaths);
}

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

336
337
338
    collectFilesList(QStringList());
}

339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
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);

354
355
356
357
358
    collectShowDescription(id);
}

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

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

    collectFilesList(QStringList()
                     << m_requestedRevisionRange.begin.id
                     << m_requestedRevisionRange.end.id);
385
386
}

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

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

407
408
409
410
411
    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);
412

413
    prepareForCollection();
414
415
416
    collectFilesContents();
}

417
void GitDiffHandler::prepareForCollection()
418
{
419
420
421
422
423
424
425
426
427
428
429
430
    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;
        }
431

432
433
434
        ++it;
    }
}
435

436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
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
461
462
                if (m_editor)
                    command->setCodec(m_editor->editorWidget()->codec());
463
                connect(command, SIGNAL(output(QString)), this, SLOT(slotFileContentsReceived(QString)));
464
465
466

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

                return;
            }
        }
476

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

    feedEditor();
481
482
}

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

488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
    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);
        }
    }
507
508
509
510
511
512
513
514

    collectFilesContents();
}

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

515
516
517
518
519
520
521
522
523
524
525
    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;

526
            DiffEditor::DiffEditorWidget::DiffFilesContents dfc;
527
528
529
530
            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];
531
532
            list.append(dfc);
        }
533
534

        ++itFile;
535
    }
536

jkobus's avatar
jkobus committed
537
    m_editor->setDiff(list, m_workingDirectory);
538
539
540
541
542
543
544
545
546
    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
547
    if (file.open(QIODevice::ReadOnly | QIODevice::Text))
jkobus's avatar
jkobus committed
548
        return m_editor->editorWidget()->codec()->toUnicode(file.readAll());
549
550
551
552
553
    return QString();
}

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

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

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

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

        setBaseArguments(args);
575
576
    }

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

class GitCommitDiffArgumentsWidget : public BaseGitDiffArgumentsWidget
{
Friedemann Kleint's avatar
Friedemann Kleint committed
586
    Q_OBJECT
587

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

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

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

private:
608
609
    QStringList m_unstagedFileNames;
    QStringList m_stagedFileNames;
610
611
612
613
};

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

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

private:
    const QString m_fileName;
};

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

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

private:
    const QString m_branchName;
};

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

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

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

private:
682
683
    GitClient *m_client;
    QString m_workingDirectory;
684
    QString m_id;
685
686
};

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

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

        setBaseArguments(args);
710
711
    }

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

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

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

734
735
736
737
738
739
740
741
742
class GitLogArgumentsWidget : public BaseGitDiffArgumentsWidget
{
    Q_OBJECT

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

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

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

private:
    GitClient *m_client;
    QString m_workingDirectory;
    bool m_enableAnnotationContextMenu;
780
    QString m_fileName;
781
782
};

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

    ~ConflictHandler()
    {
803
804
805
806
807
808
809
810
811
812
        // 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
813
        }
Orgad Shaneh's avatar
Orgad Shaneh committed
814
815
    }

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

    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;
839
    QStringList m_files;
Orgad Shaneh's avatar
Orgad Shaneh committed
840
841
};

842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
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
862

hjk's avatar
hjk committed
863
Core::IEditor *locateEditor(const char *property, const QString &entry)
con's avatar
con committed
864
{
865
866
867
    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
868
869
870
    return 0;
}

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

// 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
889
static inline VcsBase::VcsBaseOutputWindow *outputWindow()
890
{
hjk's avatar
hjk committed
891
    return VcsBase::VcsBaseOutputWindow::instance();
892
893
}

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

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

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

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

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

922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
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);
}

941
// ---------------- GitClient
942
943
944

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

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

GitClient::~GitClient()
{
}

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

Orgad Shaneh's avatar
Orgad Shaneh committed
984
QString GitClient::findGitDirForRepository(const QString &repositoryDir) const
Orgad Shaneh's avatar
Orgad Shaneh committed
985
{
986
987
988
989
    static QHash<QString, QString> repoDirCache;
    QString &res = repoDirCache[repositoryDir];
    if (!res.isEmpty())
        return res;
Orgad Shaneh's avatar
Orgad Shaneh committed
990
991
992
993
    QByteArray outputText;
    QStringList arguments;
    arguments << QLatin1String("rev-parse") << QLatin1String("--git-dir");
    fullySynchronousGit(repositoryDir, arguments, &outputText, 0, false);
994
    res = QString::fromLocal8Bit(outputText.trimmed());
995
996
997
    if (!QDir(res).isAbsolute())
        res.prepend(repositoryDir + QLatin1Char('/'));
    return res;
Orgad Shaneh's avatar
Orgad Shaneh committed
998
999
}

1000
1001
1002
1003
1004
1005
1006
1007
1008
bool GitClient::managesFile(const QString &workingDirectory, const QString &fileName) const
{
    QByteArray output;
    QStringList arguments;
    arguments << QLatin1String("ls-files") << QLatin1String("--error-unmatch") << fileName;
    return fullySynchronousGit(workingDirectory, arguments, &output, 0,
                               VcsBasePlugin::SuppressCommandLogging);
}

hjk's avatar
hjk committed
1009
VcsBase::VcsBaseEditorWidget *GitClient::findExistingVCSEditor(const char *registerDynamicProperty,
Tobias Hunger's avatar
Tobias Hunger committed
1010
                                                               const QString &dynamicPropertyValue) const
1011
{
hjk's avatar
hjk committed
1012
    VcsBase::VcsBaseEditorWidget *rc = 0;
hjk's avatar
hjk committed
1013
    Core::IEditor *outputEditor = locateEditor(registerDynamicProperty, dynamicPropertyValue);
1014
1015
1016
    if (!outputEditor)
        return 0;

1017
    // Exists already
Eike Ziller's avatar
Eike Ziller committed
1018
    Core::EditorManager::activateEditor(outputEditor);
1019
    outputEditor->document()->setContents(m_msgWait.toUtf8());
hjk's avatar
hjk committed
1020
    rc = VcsBase::VcsBaseEditorWidget::getVcsBaseEditor(outputEditor);
1021
1022
1023
1024

    return rc;
}

1025
1026
DiffEditor::DiffEditor *GitClient<