gitclient.cpp 98 KB
Newer Older
hjk's avatar
hjk committed
1
/****************************************************************************
con's avatar
con committed
2
**
hjk's avatar
hjk committed
3
4
** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
** 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>

42
#include <coreplugin/actionmanager/actionmanager.h>
hjk's avatar
hjk committed
43
#include <coreplugin/coreconstants.h>
con's avatar
con committed
44
#include <coreplugin/editormanager/editormanager.h>
hjk's avatar
hjk committed
45
46
#include <coreplugin/icore.h>
#include <coreplugin/messagemanager.h>
47
#include <coreplugin/progressmanager/progressmanager.h>
48
#include <coreplugin/vcsmanager.h>
49
#include <coreplugin/id.h>
50
#include <coreplugin/documentmanager.h>
51
#include <coreplugin/iversioncontrol.h>
52
#include <coreplugin/variablemanager.h>
53

con's avatar
con committed
54
#include <texteditor/itexteditor.h>
55
#include <utils/hostosinfo.h>
hjk's avatar
hjk committed
56
#include <utils/qtcassert.h>
57
#include <utils/qtcprocess.h>
58
#include <utils/synchronousprocess.h>
59
#include <utils/environment.h>
60
#include <utils/fileutils.h>
Tobias Hunger's avatar
Tobias Hunger committed
61
#include <vcsbase/command.h>
hjk's avatar
hjk committed
62
#include <vcsbase/vcsbaseeditor.h>
63
#include <vcsbase/vcsbaseeditorparameterwidget.h>
64
#include <vcsbase/vcsbaseoutputwindow.h>
65
#include <vcsbase/vcsbaseplugin.h>
con's avatar
con committed
66

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

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

79
static const char GIT_DIRECTORY[] = ".git";
con's avatar
con committed
80

81
82
83
namespace Git {
namespace Internal {

hjk's avatar
hjk committed
84
class BaseGitDiffArgumentsWidget : public VcsBase::VcsBaseEditorParameterWidget
85
{
Friedemann Kleint's avatar
Friedemann Kleint committed
86
    Q_OBJECT
87

88
public:
89
    BaseGitDiffArgumentsWidget(GitClient *client, const QString &directory,
90
                               const QStringList &args) :
91
        m_workingDirectory(directory),
92
        m_client(client)
93
    {
94
95
        QTC_ASSERT(!directory.isEmpty(), return);
        QTC_ASSERT(m_client, return);
96

97
98
99
        m_patienceButton = addToggleButton(QLatin1String("--patience"), tr("Patience"),
                                           tr("Use the patience algorithm for calculating the differences."));
        mapSetting(m_patienceButton, client->settings()->boolPointer(GitSettings::diffPatienceKey));
100
        m_ignoreWSButton = addToggleButton(QLatin1String("--ignore-space-change"), tr("Ignore Whitespace"),
101
102
                                           tr("Ignore whitespace only changes."));
        mapSetting(m_ignoreWSButton, m_client->settings()->boolPointer(GitSettings::ignoreSpaceChangesInDiffKey));
103
104

        setBaseArguments(args);
105
106
    }

107
protected:
108
109
    QString m_workingDirectory;
    GitClient *m_client;
110
111
    QToolButton *m_patienceButton;
    QToolButton *m_ignoreWSButton;
112
113
114
115
};

class GitCommitDiffArgumentsWidget : public BaseGitDiffArgumentsWidget
{
Friedemann Kleint's avatar
Friedemann Kleint committed
116
    Q_OBJECT
117

118
public:
119
    GitCommitDiffArgumentsWidget(Git::Internal::GitClient *client, const QString &directory,
120
121
                                 const QStringList &args, const QStringList &unstaged,
                                 const QStringList &staged) :
122
        BaseGitDiffArgumentsWidget(client, directory, args),
123
124
125
126
        m_unstagedFileNames(unstaged),
        m_stagedFileNames(staged)
    { }

127
    void executeCommand()
128
    {
129
        m_client->diff(m_workingDirectory, arguments(), m_unstagedFileNames, m_stagedFileNames);
130
131
132
133
134
135
136
137
138
    }

private:
    const QStringList m_unstagedFileNames;
    const QStringList m_stagedFileNames;
};

class GitFileDiffArgumentsWidget : public BaseGitDiffArgumentsWidget
{
Friedemann Kleint's avatar
Friedemann Kleint committed
139
    Q_OBJECT
140
public:
141
    GitFileDiffArgumentsWidget(Git::Internal::GitClient *client, const QString &directory,
142
                               const QStringList &args, const QString &file) :
143
        BaseGitDiffArgumentsWidget(client, directory, args),
144
145
146
        m_fileName(file)
    { }

147
    void executeCommand()
148
    {
149
        m_client->diff(m_workingDirectory, arguments(), m_fileName);
150
151
152
153
154
155
156
157
    }

private:
    const QString m_fileName;
};

class GitBranchDiffArgumentsWidget : public BaseGitDiffArgumentsWidget
{
Friedemann Kleint's avatar
Friedemann Kleint committed
158
    Q_OBJECT
159
public:
160
    GitBranchDiffArgumentsWidget(Git::Internal::GitClient *client, const QString &directory,
161
                                 const QStringList &args, const QString &branch) :
162
        BaseGitDiffArgumentsWidget(client, directory, args),
163
164
165
        m_branchName(branch)
    { }

166
    void executeCommand()
167
    {
168
        m_client->diffBranch(m_workingDirectory, arguments(), m_branchName);
169
170
171
172
173
174
    }

private:
    const QString m_branchName;
};

Orgad Shaneh's avatar
Orgad Shaneh committed
175
class GitShowArgumentsWidget : public BaseGitDiffArgumentsWidget
176
{
Friedemann Kleint's avatar
Friedemann Kleint committed
177
    Q_OBJECT
178

179
public:
180
    GitShowArgumentsWidget(Git::Internal::GitClient *client,
181
182
183
                           const QString &directory,
                           const QStringList &args,
                           const QString &id) :
Orgad Shaneh's avatar
Orgad Shaneh committed
184
        BaseGitDiffArgumentsWidget(client, directory, args),
185
186
        m_client(client),
        m_workingDirectory(directory),
187
188
        m_id(id)
    {
189
190
191
192
193
194
195
196
197
        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"));
        mapSetting(addComboBox(QLatin1String("--pretty"), prettyChoices),
198
                   m_client->settings()->intPointer(GitSettings::showPrettyFormatKey));
199
200
201
    }

    void executeCommand()
202
    {
203
        m_client->show(m_workingDirectory, m_id, arguments());
204
205
206
    }

private:
207
208
    GitClient *m_client;
    QString m_workingDirectory;
209
    QString m_id;
210
211
};

hjk's avatar
hjk committed
212
class GitBlameArgumentsWidget : public VcsBase::VcsBaseEditorParameterWidget
213
{
Friedemann Kleint's avatar
Friedemann Kleint committed
214
    Q_OBJECT
215

216
public:
217
218
219
220
    GitBlameArgumentsWidget(Git::Internal::GitClient *client,
                            const QString &directory,
                            const QStringList &args,
                            const QString &revision, const QString &fileName) :
221
        m_editor(0),
222
223
        m_client(client),
        m_workingDirectory(directory),
224
225
226
        m_revision(revision),
        m_fileName(fileName)
    {
227
228
229
        mapSetting(addToggleButton(QString(), tr("Omit Date"),
                                   tr("Hide the date of a change from the output.")),
                   m_client->settings()->boolPointer(GitSettings::omitAnnotationDateKey));
230
        mapSetting(addToggleButton(QLatin1String("-w"), tr("Ignore Whitespace"),
231
232
                                   tr("Ignore whitespace only changes.")),
                   m_client->settings()->boolPointer(GitSettings::ignoreSpaceChangesInBlameKey));
233
234

        setBaseArguments(args);
235
236
    }

hjk's avatar
hjk committed
237
    void setEditor(VcsBase::VcsBaseEditorWidget *editor)
238
    {
239
        QTC_ASSERT(editor, return);
240
241
242
        m_editor = editor;
    }

243
    void executeCommand()
244
    {
245
246
247
        int line = -1;
        if (m_editor)
            line = m_editor->lineNumberOfCurrentEditor();
248
        m_client->blame(m_workingDirectory, arguments(), m_fileName, m_revision, line);
249
250
251
    }

private:
hjk's avatar
hjk committed
252
    VcsBase::VcsBaseEditorWidget *m_editor;
253
254
    GitClient *m_client;
    QString m_workingDirectory;
255
256
257
258
    QString m_revision;
    QString m_fileName;
};

259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
class GitLogArgumentsWidget : public BaseGitDiffArgumentsWidget
{
    Q_OBJECT

public:
    GitLogArgumentsWidget(Git::Internal::GitClient *client,
                          const QString &directory,
                          bool enableAnnotationContextMenu,
                          const QStringList &args,
                          const QStringList &fileNames) :
        BaseGitDiffArgumentsWidget(client, directory, args),
        m_client(client),
        m_workingDirectory(directory),
        m_enableAnnotationContextMenu(enableAnnotationContextMenu),
        m_fileNames(fileNames)
    {
        QToolButton *button = addToggleButton(QLatin1String("--patch"), tr("Show Diff"),
                                              tr("Show difference."));
        mapSetting(button, m_client->settings()->boolPointer(GitSettings::logDiffKey));
        connect(button, SIGNAL(toggled(bool)), m_patienceButton, SLOT(setEnabled(bool)));
        connect(button, SIGNAL(toggled(bool)), m_ignoreWSButton, SLOT(setEnabled(bool)));
        m_patienceButton->setEnabled(button->isChecked());
        m_ignoreWSButton->setEnabled(button->isChecked());
    }

    void executeCommand()
    {
286
        m_client->log(m_workingDirectory, m_fileNames, m_enableAnnotationContextMenu, arguments());
287
288
289
290
291
292
293
294
295
    }

private:
    GitClient *m_client;
    QString m_workingDirectory;
    bool m_enableAnnotationContextMenu;
    QStringList m_fileNames;
};

hjk's avatar
hjk committed
296
Core::IEditor *locateEditor(const char *property, const QString &entry)
con's avatar
con committed
297
{
hjk's avatar
hjk committed
298
    foreach (Core::IEditor *ed, Core::ICore::editorManager()->openedEditors())
299
        if (ed->document()->property(property).toString() == entry)
con's avatar
con committed
300
301
302
303
            return ed;
    return 0;
}

304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
// Return converted command output, remove '\r' read on Windows
static inline QString commandOutputFromLocal8Bit(const QByteArray &a)
{
    QString output = QString::fromLocal8Bit(a);
    output.remove(QLatin1Char('\r'));
    return output;
}

// 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
324
static inline VcsBase::VcsBaseOutputWindow *outputWindow()
325
{
hjk's avatar
hjk committed
326
    return VcsBase::VcsBaseOutputWindow::instance();
327
328
}

329
330
static inline QString msgRepositoryNotFound(const QString &dir)
{
Tobias Hunger's avatar
Tobias Hunger committed
331
    return GitClient::tr("Cannot determine the repository for \"%1\".").arg(dir);
332
333
334
335
}

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

339
340
341
342
343
static inline QString currentDocumentPath()
{
    return Core::VariableManager::instance()->value("CurrentDocument:Path");
}

344
// ---------------- GitClient
345
346
347

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

348
349
GitClient::GitClient(GitSettings *settings) :
    m_cachedGitVersion(0),
Tobias Hunger's avatar
Tobias Hunger committed
350
    m_msgWait(tr("Waiting for data...")),
351
    m_repositoryChangedSignalMapper(0),
352
    m_settings(settings)
con's avatar
con committed
353
{
354
    QTC_CHECK(settings);
hjk's avatar
hjk committed
355
    connect(Core::ICore::instance(), SIGNAL(saveSettingsRequested()), this, SLOT(saveSettings()));
con's avatar
con committed
356
357
358
359
360
361
}

GitClient::~GitClient()
{
}

362
const char *GitClient::noColorOption = "--no-color";
363
const char *GitClient::decorateOption = "--decorate";
364

con's avatar
con committed
365
366
QString GitClient::findRepositoryForDirectory(const QString &dir)
{
Orgad Shaneh's avatar
Orgad Shaneh committed
367
    if (gitVersion() >= 0x010700) {
368
369
370
371
372
373
374
375
376
377
378
379
380
381
        // Find a directory to run git in:
        const QString root = QDir::rootPath();
        const QString home = QDir::homePath();

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

            if (directory.exists())
                break;
        } while (directory.cdUp());

Orgad Shaneh's avatar
Orgad Shaneh committed
382
383
384
        QByteArray outputText;
        QStringList arguments;
        arguments << QLatin1String("rev-parse") << QLatin1String("--show-toplevel");
385
        fullySynchronousGit(directory.absolutePath(), arguments, &outputText, 0, false);
386
        return QString::fromLocal8Bit(outputText.trimmed());
Orgad Shaneh's avatar
Orgad Shaneh committed
387
388
389
390
391
    } else {
        // Check for ".git/config"
        const QString checkFile = QLatin1String(GIT_DIRECTORY) + QLatin1String("/config");
        return VcsBase::VcsBasePlugin::findRepositoryForDirectory(dir, checkFile);
    }
con's avatar
con committed
392
393
}

Orgad Shaneh's avatar
Orgad Shaneh committed
394
395
QString GitClient::findGitDirForRepository(const QString &repositoryDir)
{
396
397
398
399
    static QHash<QString, QString> repoDirCache;
    QString &res = repoDirCache[repositoryDir];
    if (!res.isEmpty())
        return res;
Orgad Shaneh's avatar
Orgad Shaneh committed
400
401
402
403
    QByteArray outputText;
    QStringList arguments;
    arguments << QLatin1String("rev-parse") << QLatin1String("--git-dir");
    fullySynchronousGit(repositoryDir, arguments, &outputText, 0, false);
404
    res = QString::fromLocal8Bit(outputText.trimmed());
405
406
407
    if (!QDir(res).isAbsolute())
        res.prepend(repositoryDir + QLatin1Char('/'));
    return res;
Orgad Shaneh's avatar
Orgad Shaneh committed
408
409
}

hjk's avatar
hjk committed
410
VcsBase::VcsBaseEditorWidget *GitClient::findExistingVCSEditor(const char *registerDynamicProperty,
Tobias Hunger's avatar
Tobias Hunger committed
411
                                                               const QString &dynamicPropertyValue) const
412
{
hjk's avatar
hjk committed
413
    VcsBase::VcsBaseEditorWidget *rc = 0;
hjk's avatar
hjk committed
414
    Core::IEditor *outputEditor = locateEditor(registerDynamicProperty, dynamicPropertyValue);
415
416
417
    if (!outputEditor)
        return 0;

418
    // Exists already
hjk's avatar
hjk committed
419
    Core::EditorManager::activateEditor(outputEditor, Core::EditorManager::ModeSwitch);
420
    outputEditor->createNew(m_msgWait);
hjk's avatar
hjk committed
421
    rc = VcsBase::VcsBaseEditorWidget::getVcsBaseEditor(outputEditor);
422
423
424
425

    return rc;
}

con's avatar
con committed
426
427
428
429
/* Create an editor associated to VCS output of a source file/directory
 * (using the file's codec). Makes use of a dynamic property to find an
 * existing instance and to reuse it (in case, say, 'git diff foo' is
 * already open). */
hjk's avatar
hjk committed
430
VcsBase::VcsBaseEditorWidget *GitClient::createVcsEditor(const Core::Id &id,
Tobias Hunger's avatar
Tobias Hunger committed
431
432
433
                                                         QString title,
                                                         // Source file or directory
                                                         const QString &source,
434
                                                         CodecType codecType,
Tobias Hunger's avatar
Tobias Hunger committed
435
436
437
438
                                                         // Dynamic property and value to identify that editor
                                                         const char *registerDynamicProperty,
                                                         const QString &dynamicPropertyValue,
                                                         QWidget *configWidget) const
con's avatar
con committed
439
{
hjk's avatar
hjk committed
440
    VcsBase::VcsBaseEditorWidget *rc = 0;
441
    QTC_CHECK(!findExistingVCSEditor(registerDynamicProperty, dynamicPropertyValue));
442
443

    // Create new, set wait message, set up with source and codec
hjk's avatar
hjk committed
444
    Core::IEditor *outputEditor = Core::EditorManager::openEditorWithContents(id, &title, m_msgWait);
445
    outputEditor->document()->setProperty(registerDynamicProperty, dynamicPropertyValue);
hjk's avatar
hjk committed
446
    rc = VcsBase::VcsBaseEditorWidget::getVcsBaseEditor(outputEditor);
447
448
449
450
    connect(rc, SIGNAL(annotateRevisionRequested(QString,QString,int)),
            this, SLOT(slotBlameRevisionRequested(QString,QString,int)));
    QTC_ASSERT(rc, return 0);
    rc->setSource(source);
451
    if (codecType == CodecSource) {
452
        rc->setCodec(getSourceCodec(source));
453
454
455
456
457
458
    } else if (codecType == CodecLogOutput) {
        QString encodingName = readConfigValue(source, QLatin1String("i18n.logOutputEncoding"));
        if (encodingName.isEmpty())
            encodingName = QLatin1String("utf-8");
        rc->setCodec(QTextCodec::codecForName(encodingName.toLocal8Bit()));
    }
459

460
    rc->setForceReadOnly(true);
hjk's avatar
hjk committed
461
    Core::EditorManager::activateEditor(outputEditor, Core::EditorManager::ModeSwitch);
462
463
464
465

    if (configWidget)
        rc->setConfigurationWidget(configWidget);

con's avatar
con committed
466
467
468
    return rc;
}

469
470
void GitClient::diff(const QString &workingDirectory,
                     const QStringList &diffArgs,
471
472
                     const QStringList &unstagedFileNames,
                     const QStringList &stagedFileNames)
con's avatar
con committed
473
{
474
    const QString binary = settings()->stringValue(GitSettings::binaryPathKey);
hjk's avatar
hjk committed
475
    const Core::Id editorId = Git::Constants::GIT_DIFF_EDITOR_ID;
con's avatar
con committed
476
477
    const QString title = tr("Git Diff");

hjk's avatar
hjk committed
478
    VcsBase::VcsBaseEditorWidget *editor = findExistingVCSEditor("originalFileName", workingDirectory);
479
480
    if (!editor) {
        GitCommitDiffArgumentsWidget *argWidget =
481
                new GitCommitDiffArgumentsWidget(this, workingDirectory, diffArgs,
482
483
                                                 unstagedFileNames, stagedFileNames);

hjk's avatar
hjk committed
484
        editor = createVcsEditor(editorId, title,
485
                                 workingDirectory, CodecSource, "originalFileName", workingDirectory, argWidget);
hjk's avatar
hjk committed
486
        connect(editor, SIGNAL(diffChunkReverted(VcsBase::DiffChunk)), argWidget, SLOT(executeCommand()));
487
    }
488
489
490

    GitCommitDiffArgumentsWidget *argWidget = qobject_cast<GitCommitDiffArgumentsWidget *>(editor->configurationWidget());
    QStringList userDiffArgs = argWidget->arguments();
491
    editor->setDiffBaseDirectory(workingDirectory);
con's avatar
con committed
492

493
494
495
    // Create a batch of 2 commands to be run after each other in case
    // we have a mixture of staged/unstaged files as is the case
    // when using the submit dialog.
hjk's avatar
hjk committed
496
    VcsBase::Command *command = createCommand(workingDirectory, editor);
497
    // Directory diff?
498
499
500
501

    QStringList cmdArgs;
    cmdArgs << QLatin1String("diff") << QLatin1String(noColorOption);

502
503
    int timeout = settings()->intValue(GitSettings::timeoutKey);

504
    if (unstagedFileNames.empty() && stagedFileNames.empty()) {
505
506
       QStringList arguments(cmdArgs);
       arguments << userDiffArgs;
507
       outputWindow()->appendCommand(workingDirectory, binary, arguments);
508
       command->addJob(arguments, timeout);
509
510
511
    } else {
        // Files diff.
        if (!unstagedFileNames.empty()) {
512
513
           QStringList arguments(cmdArgs);
           arguments << userDiffArgs;
514
           arguments << QLatin1String("--") << unstagedFileNames;
515
           outputWindow()->appendCommand(workingDirectory, binary, arguments);
516
           command->addJob(arguments, timeout);
517
518
        }
        if (!stagedFileNames.empty()) {
519
520
           QStringList arguments(cmdArgs);
           arguments << userDiffArgs;
521
           arguments << QLatin1String("--cached") << diffArgs << QLatin1String("--") << stagedFileNames;
522
           outputWindow()->appendCommand(workingDirectory, binary, arguments);
523
           command->addJob(arguments, timeout);
524
525
526
        }
    }
    command->execute();
con's avatar
con committed
527
528
}

529
530
531
void GitClient::diff(const QString &workingDirectory,
                     const QStringList &diffArgs,
                     const QString &fileName)
con's avatar
con committed
532
{
hjk's avatar
hjk committed
533
    const Core::Id editorId = Git::Constants::GIT_DIFF_EDITOR_ID;
Tobias Hunger's avatar
Tobias Hunger committed
534
    const QString title = tr("Git Diff \"%1\"").arg(fileName);
hjk's avatar
hjk committed
535
    const QString sourceFile = VcsBase::VcsBaseEditorWidget::getSource(workingDirectory, fileName);
536

hjk's avatar
hjk committed
537
    VcsBase::VcsBaseEditorWidget *editor = findExistingVCSEditor("originalFileName", sourceFile);
538
539
    if (!editor) {
        GitFileDiffArgumentsWidget *argWidget =
540
                new GitFileDiffArgumentsWidget(this, workingDirectory, diffArgs, fileName);
541

hjk's avatar
hjk committed
542
543
        editor = createVcsEditor(editorId, title, sourceFile, CodecSource, "originalFileName", sourceFile, argWidget);
        connect(editor, SIGNAL(diffChunkReverted(VcsBase::DiffChunk)), argWidget, SLOT(executeCommand()));
544
    }
Tobias Hunger's avatar
Tobias Hunger committed
545
    editor->setDiffBaseDirectory(workingDirectory);
546

547
548
549
    GitFileDiffArgumentsWidget *argWidget = qobject_cast<GitFileDiffArgumentsWidget *>(editor->configurationWidget());
    QStringList userDiffArgs = argWidget->arguments();

550
551
552
553
554
555
556
    QStringList cmdArgs;
    cmdArgs << QLatin1String("diff") << QLatin1String(noColorOption)
              << userDiffArgs;

    if (!fileName.isEmpty())
        cmdArgs << QLatin1String("--") << fileName;
    executeGit(workingDirectory, cmdArgs, editor);
con's avatar
con committed
557
558
}

559
560
561
562
void GitClient::diffBranch(const QString &workingDirectory,
                           const QStringList &diffArgs,
                           const QString &branchName)
{
hjk's avatar
hjk committed
563
    const Core::Id editorId = Git::Constants::GIT_DIFF_EDITOR_ID;
Tobias Hunger's avatar
Tobias Hunger committed
564
    const QString title = tr("Git Diff Branch \"%1\"").arg(branchName);
hjk's avatar
hjk committed
565
    const QString sourceFile = VcsBase::VcsBaseEditorWidget::getSource(workingDirectory, QStringList());
566

hjk's avatar
hjk committed
567
    VcsBase::VcsBaseEditorWidget *editor = findExistingVCSEditor("BranchName", branchName);
568
    if (!editor)
hjk's avatar
hjk committed
569
        editor = createVcsEditor(editorId, title, sourceFile, CodecSource, "BranchName", branchName,
570
                                 new GitBranchDiffArgumentsWidget(this, workingDirectory,
571
                                                                  diffArgs, branchName));
Tobias Hunger's avatar
Tobias Hunger committed
572
    editor->setDiffBaseDirectory(workingDirectory);
573

574
575
    GitBranchDiffArgumentsWidget *argWidget = qobject_cast<GitBranchDiffArgumentsWidget *>(editor->configurationWidget());
    QStringList userDiffArgs = argWidget->arguments();
576
577
578

    QStringList cmdArgs;
    cmdArgs << QLatin1String("diff") << QLatin1String(noColorOption)
579
              << userDiffArgs  << branchName;
580
581

    executeGit(workingDirectory, cmdArgs, editor);
582
583
}

584
585
586
587
588
589
590
void GitClient::merge(const QString &workingDirectory, const QStringList &unmergedFileNames)
{
    MergeTool *mergeTool = new MergeTool(this);
    if (!mergeTool->start(workingDirectory, unmergedFileNames))
        delete mergeTool;
}

con's avatar
con committed
591
592
void GitClient::status(const QString &workingDirectory)
{
593
    // @TODO: Use "--no-color" once it is supported
594
595
    QStringList statusArgs(QLatin1String("status"));
    statusArgs << QLatin1String("-u");
hjk's avatar
hjk committed
596
    VcsBase::VcsBaseOutputWindow *outwin = outputWindow();
597
    outwin->setRepository(workingDirectory);
hjk's avatar
hjk committed
598
    VcsBase::Command *command = executeGit(workingDirectory, statusArgs, 0, true);
599
    connect(command, SIGNAL(finished(bool,int,QVariant)), outwin, SLOT(clearRepository()),
600
            Qt::QueuedConnection);
con's avatar
con committed
601
602
}

603
static const char graphLogFormatC[] = "%h %d %an %s %ci";
604
605

// Create a graphical log.
606
void GitClient::graphLog(const QString &workingDirectory, const QString & branch)
607
608
609
610
{
    QStringList arguments;
    arguments << QLatin1String("log") << QLatin1String(noColorOption);

611
612
613
    int logCount = settings()->intValue(GitSettings::logCountKey);
    if (logCount > 0)
         arguments << QLatin1String("-n") << QString::number(logCount);
614
615
616
    arguments << (QLatin1String("--pretty=format:") +  QLatin1String(graphLogFormatC))
              << QLatin1String("--topo-order") <<  QLatin1String("--graph");

617
618
619
620
    QString title;
    if (branch.isEmpty()) {
        title = tr("Git Log");
    } else {
Tobias Hunger's avatar
Tobias Hunger committed
621
        title = tr("Git Log \"%1\"").arg(branch);
622
623
        arguments << branch;
    }
hjk's avatar
hjk committed
624
    const Core::Id editorId = Git::Constants::GIT_LOG_EDITOR_ID;
hjk's avatar
hjk committed
625
626
    const QString sourceFile = VcsBase::VcsBaseEditorWidget::getSource(workingDirectory, QStringList());
    VcsBase::VcsBaseEditorWidget *editor = findExistingVCSEditor("logFileName", sourceFile);
627
    if (!editor)
hjk's avatar
hjk committed
628
        editor = createVcsEditor(editorId, title, sourceFile, CodecLogOutput, "logFileName", sourceFile, 0);
629
630
631
    executeGit(workingDirectory, arguments, editor);
}

632
void GitClient::log(const QString &workingDirectory, const QStringList &fileNames,
633
                    bool enableAnnotationContextMenu, const QStringList &args)
con's avatar
con committed
634
{
635
    const QString msgArg = fileNames.empty() ? workingDirectory :
636
                           fileNames.join(QLatin1String(", "));
637
638
    const QString title = tr("Git Log \"%1\"").arg(msgArg);
    const Core::Id editorId = Git::Constants::GIT_LOG_EDITOR_ID;
hjk's avatar
hjk committed
639
640
    const QString sourceFile = VcsBase::VcsBaseEditorWidget::getSource(workingDirectory, fileNames);
    VcsBase::VcsBaseEditorWidget *editor = findExistingVCSEditor("logFileName", sourceFile);
641
    if (!editor)
hjk's avatar
hjk committed
642
        editor = createVcsEditor(editorId, title, sourceFile, CodecLogOutput, "logFileName", sourceFile,
643
644
645
646
647
                                 new GitLogArgumentsWidget(this, workingDirectory,
                                                           enableAnnotationContextMenu,
                                                           args, fileNames));
    editor->setFileLogAnnotateEnabled(enableAnnotationContextMenu);

648
    QStringList arguments;
649
650
    arguments << QLatin1String("log") << QLatin1String(noColorOption)
              << QLatin1String(decorateOption);
651

652
653
654
    int logCount = settings()->intValue(GitSettings::logCountKey);
    if (logCount > 0)
         arguments << QLatin1String("-n") << QString::number(logCount);
655

656
657
658
659
660
    GitLogArgumentsWidget *argWidget = qobject_cast<GitLogArgumentsWidget *>(editor->configurationWidget());
    QStringList userArgs = argWidget->arguments();

    arguments.append(userArgs);

661
662
    if (!fileNames.isEmpty())
        arguments.append(fileNames);
con's avatar
con committed
663

664
    executeGit(workingDirectory, arguments, editor);
con's avatar
con committed
665
666
}

667
668
669
670
671
672
673
674
675
676
677
678
// Do not show "0000" or "^32ae4"
static inline bool canShow(const QString &sha)
{
    if (sha.startsWith(QLatin1Char('^')))
        return false;
    if (sha.count(QLatin1Char('0')) == sha.size())
        return false;
    return true;
}

static inline QString msgCannotShow(const QString &sha)
{
Tobias Hunger's avatar
Tobias Hunger committed
679
    return GitClient::tr("Cannot describe \"%1\".").arg(sha);
680
681
}

682
void GitClient::show(const QString &source, const QString &id, const QStringList &args)
con's avatar
con committed
683
{
684
685
686
687
688
    if (!canShow(id)) {
        outputWindow()->append(msgCannotShow(id));
        return;
    }

Tobias Hunger's avatar
Tobias Hunger committed
689
    const QString title = tr("Git Show \"%1\"").arg(id);
hjk's avatar
hjk committed
690
    const Core::Id editorId = Git::Constants::GIT_DIFF_EDITOR_ID;
hjk's avatar
hjk committed
691
    VcsBase::VcsBaseEditorWidget *editor = findExistingVCSEditor("show", id);
692
    if (!editor)
hjk's avatar
hjk committed
693
        editor = createVcsEditor(editorId, title, source, CodecSource, "show", id,
694
                                 new GitShowArgumentsWidget(this, source, args, id));
695
696
697

    GitShowArgumentsWidget *argWidget = qobject_cast<GitShowArgumentsWidget *>(editor->configurationWidget());
    QStringList userArgs = argWidget->arguments();
698
699
700

    QStringList arguments;
    arguments << QLatin1String("show") << QLatin1String(noColorOption);
701
    arguments << QLatin1String(decorateOption);
702
703
    arguments.append(userArgs);
    arguments << id;
con's avatar
con committed
704
705
706

    const QFileInfo sourceFi(source);
    const QString workDir = sourceFi.isDir() ? sourceFi.absoluteFilePath() : sourceFi.absolutePath();
Tobias Hunger's avatar
Tobias Hunger committed
707
    editor->setDiffBaseDirectory(workDir);
708
    executeGit(workDir, arguments, editor);
con's avatar
con committed
709
710
}

Tobias Hunger's avatar
Tobias Hunger committed
711
712
void GitClient::saveSettings()
{
hjk's avatar
hjk committed
713
    settings()->writeSettings(Core::ICore::settings());
Tobias Hunger's avatar
Tobias Hunger committed
714
715
}

716
717
718
719
720
721
722
723
void GitClient::slotBlameRevisionRequested(const QString &source, QString change, int lineNumber)
{
    // This might be invoked with a verbose revision description
    // "SHA1 author subject" from the annotation context menu. Strip the rest.
    const int blankPos = change.indexOf(QLatin1Char(' '));
    if (blankPos != -1)
        change.truncate(blankPos);
    const QFileInfo fi(source);
724
    blame(fi.absolutePath(), QStringList(), fi.fileName(), change, lineNumber);
725
726
}

727
728
729
730
731
732
733
734
735
736
737
738
void GitClient::appendOutputData(const QByteArray &data) const
{
    const QTextCodec *codec = getSourceCodec(currentDocumentPath());
    outputWindow()->appendData(codec->toUnicode(data).toLocal8Bit());
}

void GitClient::appendOutputDataSilently(const QByteArray &data) const
{
    const QTextCodec *codec = getSourceCodec(currentDocumentPath());
    outputWindow()->appendDataSilently(codec->toUnicode(data).toLocal8Bit());
}

739
740
741
742
743
744
745
746
747
748
QTextCodec *GitClient::getSourceCodec(const QString &file) const
{
    if (QFileInfo(file).isFile())
        return VcsBase::VcsBaseEditorWidget::getCodec(file);
    QString encodingName = readConfigValue(file, QLatin1String("gui.encoding"));
    if (encodingName.isEmpty())
        encodingName = QLatin1String("utf-8");
    return QTextCodec::codecForName(encodingName.toLocal8Bit());
}

749
void GitClient::blame(const QString &workingDirectory,
750
                      const QStringList &args,
751
                      const QString &fileName,
Tobias Hunger's avatar
Tobias Hunger committed
752
753
                      const QString &revision,
                      int lineNumber)
con's avatar
con committed
754
{
hjk's avatar
hjk committed
755
    const Core::Id editorId = Git::Constants::GIT_BLAME_EDITOR_ID;
hjk's avatar
hjk committed
756
    const QString id = VcsBase::VcsBaseEditorWidget::getTitleId(workingDirectory, QStringList(fileName), revision);
Tobias Hunger's avatar
Tobias Hunger committed
757
    const QString title = tr("Git Blame \"%1\"").arg(id);
hjk's avatar
hjk committed
758
    const QString sourceFile = VcsBase::VcsBaseEditorWidget::getSource(workingDirectory, fileName);
con's avatar
con committed
759

hjk's avatar
hjk committed
760
    VcsBase::VcsBaseEditorWidget *editor = findExistingVCSEditor("blameFileName", id);
761
762
    if (!editor) {
        GitBlameArgumentsWidget *argWidget =
763
                new GitBlameArgumentsWidget(this, workingDirectory, args,
764
                                            revision, fileName);
hjk's avatar
hjk committed
765
        editor = createVcsEditor(editorId, title, sourceFile, CodecSource, "blameFileName", id, argWidget);
766
767
768
        argWidget->setEditor(editor);
    }

769
770
771
    GitBlameArgumentsWidget *argWidget = qobject_cast<GitBlameArgumentsWidget *>(editor->configurationWidget());
    QStringList userBlameArgs = argWidget->arguments();

772
773
774
775
776
777
    QStringList arguments(QLatin1String("blame"));
    arguments << QLatin1String("--root");
    arguments.append(userBlameArgs);
    arguments << QLatin1String("--") << fileName;
    if (!revision.isEmpty())
        arguments << revision;
hjk's avatar
hjk committed
778
    executeGit(workingDirectory, arguments, editor, false, VcsBase::Command::NoReport, lineNumber);
con's avatar
con committed
779
780
}

781
782
783
784
void GitClient::checkoutBranch(const QString &workingDirectory, const QString &branch)
{
    QStringList arguments(QLatin1String("checkout"));
    arguments <<  branch;
hjk's avatar
hjk committed
785
    VcsBase::Command *cmd = executeGit(workingDirectory, arguments, 0, true);
786
    connectRepositoryChanged(workingDirectory, cmd);
787
788
}

789
bool GitClient::synchronousCheckoutBranch(const QString &workingDirectory,
Tobias Hunger's avatar
Tobias Hunger committed
790
791
                                          const QString &branch,
                                          QString *errorMessage /* = 0 */)
792
793
794
795
796
{
    QByteArray outputText;
    QByteArray errorText;
    QStringList arguments;
    arguments << QLatin1String("checkout") << branch;
797
    const bool rc = fullySynchronousGit(workingDirectory, arguments, &outputText, &errorText);
798
    const QString output = commandOutputFromLocal8Bit(outputText);
799
    outputWindow()->append(output);
800
801
    if (!rc) {
        const QString stdErr = commandOutputFromLocal8Bit(errorText);
Friedemann Kleint's avatar
Friedemann Kleint committed
802
        //: Meaning of the arguments: %1: Branch, %2: Repository, %3: Error message
Tobias Hunger's avatar
Tobias Hunger committed
803
        const QString msg = tr("Cannot checkout \"%1\" of \"%2\": %3").arg(branch, workingDirectory, stdErr);
804
        if (errorMessage)
805
            *errorMessage = msg;
806
        else
807
            outputWindow()->appendError(msg);
808
809
810
811
812
        return false;
    }
    return true;
}

con's avatar
con committed
813
814
815
816
817
818
819
820
821
822
823
void GitClient::checkout(const QString &workingDirectory, const QString &fileName)
{
    // Passing an empty argument as the file name is very dangereous, since this makes
    // git checkout apply to all files. Almost looks like a bug in git.
    if (fileName.isEmpty())
        return;

    QStringList arguments;
    arguments << QLatin1String("checkout") << QLatin1String("HEAD") << QLatin1String("--")
            << fileName;

824
    executeGit(workingDirectory, arguments, 0, true);
con's avatar
con committed
825
826
827
828
829
830
831
832
833
}

void GitClient::hardReset(const QString &workingDirectory, const QString &commit)
{
    QStringList arguments;
    arguments << QLatin1String("reset") << QLatin1String("--hard");
    if (!commit.isEmpty())
        arguments << commit;

Petar Perisin's avatar
Petar Perisin committed
834
835
836
837
838
839
840
841
842
843
844
845
    VcsBase::Command *cmd = executeGit(workingDirectory, arguments, 0, true);
    connectRepositoryChanged(workingDirectory, cmd);
}

void GitClient::softReset(const QString &workingDirectory, const QString &commit)
{
    if (commit.isEmpty())
        return;

    QStringList arguments;
    arguments << QLatin1String("reset") << QLatin1String("--soft") << commit;

hjk's avatar
hjk committed
846
    VcsBase::Command *cmd = executeGit(workingDirectory, arguments, 0, true);
847
    connectRepositoryChanged(workingDirectory, cmd);
con's avatar
con committed
848
849
850
851
852
853
854
}

void GitClient::addFile(const QString &workingDirectory, const QString &fileName)
{
    QStringList arguments;
    arguments << QLatin1String("add") << fileName;

855
    executeGit(workingDirectory, arguments, 0, true);
con's avatar
con committed
856
857
}

858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
bool GitClient::synchronousLog(const QString &workingDirectory, const QStringList &arguments,
                               QString *output, QString *errorMessageIn)
{
    QByteArray outputText;
    QByteArray errorText;
    QStringList allArguments;
    allArguments << QLatin1String("log") << QLatin1String(GitClient::noColorOption);
    allArguments.append(arguments);
    const bool rc = fullySynchronousGit(workingDirectory, allArguments, &outputText, &errorText);
    if (rc) {
        *output = commandOutputFromLocal8Bit(outputText);
    } else {
        const QString errorMessage = tr("Cannot obtain log of \"%1\": %2").
                                     arg(QDir::toNativeSeparators(workingDirectory),
                                         commandOutputFromLocal8Bit(errorText));
873
        if (errorMessageIn)
874
            *errorMessageIn = errorMessage;
875
        else
876
877
878
879
880
            outputWindow()->appendError(errorMessage);
    }
    return rc;
}

881
882
883
884
// Warning: 'intendToAdd' works only from 1.6.1 onwards
bool GitClient::synchronousAdd(const QString &workingDirectory,
                               bool intendToAdd,
                               const QStringList &files)
con's avatar
con committed
885
886
887
888
{
    QByteArray outputText;
    QByteArray errorText;
    QStringList arguments;
889
890
891
892
    arguments << QLatin1String("add");
    if (intendToAdd)
        arguments << QLatin1String("--intent-to-add");
    arguments.append(files);
893
    const bool rc = fullySynchronousGit(workingDirectory, arguments, &outputText, &errorText);
con's avatar
con committed
894
    if (!rc) {
Tobias Hunger's avatar
Tobias Hunger committed
895
        const QString errorMessage = tr("Cannot add %n file(s) to \"%1\": %2", 0, files.size()).
896
897
                                     arg(QDir::toNativeSeparators(workingDirectory),
                                     commandOutputFromLocal8Bit(errorText));
898
        outputWindow()->appendError(errorMessage);
con's avatar
con committed
899
900
901
902
    }
    return rc;
}

903
904
905
906
907
908
909
910
911
912
913
bool GitClient::synchronousDelete(const QString &workingDirectory,
                                  bool force,
                                  const QStringList &files)
{
    QByteArray outputText;
    QByteArray errorText;
    QStringList arguments;
    arguments << QLatin1String("rm");
    if (force)
        arguments << QLatin1String("--force");
    arguments.append(files);