gitclient.cpp 93.9 KB
Newer Older
1
/**************************************************************************
con's avatar
con committed
2
3
4
**
** This file is part of Qt Creator
**
hjk's avatar
hjk committed
5
** Copyright (c) 2012 Nokia Corporation and/or its subsidiary(-ies).
con's avatar
con committed
6
**
7
** Contact: Nokia Corporation (qt-info@nokia.com)
con's avatar
con committed
8
**
9
**
10
** GNU Lesser General Public License Usage
11
**
hjk's avatar
hjk committed
12
13
14
15
16
17
** 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.
18
**
con's avatar
con committed
19
** In addition, as a special exception, Nokia gives you certain additional
hjk's avatar
hjk committed
20
** rights. These rights are described in the Nokia Qt LGPL Exception
con's avatar
con committed
21
22
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
hjk's avatar
hjk committed
23
24
25
26
27
** Other Usage
**
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
con's avatar
con committed
28
** If you have questions regarding the use of this file, please contact
29
** Nokia at qt-info@nokia.com.
con's avatar
con committed
30
**
31
**************************************************************************/
hjk's avatar
hjk committed
32

con's avatar
con committed
33
#include "gitclient.h"
34
#include "gitutils.h"
hjk's avatar
hjk committed
35

con's avatar
con committed
36
#include "commitdata.h"
hjk's avatar
hjk committed
37
38
#include "gitconstants.h"
#include "gitplugin.h"
39
#include "gitsubmiteditor.h"
40
#include "gitversioncontrol.h"
con's avatar
con committed
41

42
43
#include <vcsbase/submitfilemodel.h>

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

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

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

75
76
77
78
79
#include <QComboBox>
#include <QMainWindow> // for msg box parent
#include <QMessageBox>
#include <QToolButton>
#include <QTextCodec>
con's avatar
con committed
80

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

83
84
85
namespace Git {
namespace Internal {

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

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

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

        setBaseArguments(args);
107
108
    }

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

class GitCommitDiffArgumentsWidget : public BaseGitDiffArgumentsWidget
{
Friedemann Kleint's avatar
Friedemann Kleint committed
118
    Q_OBJECT
119

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

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

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

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

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

private:
    const QString m_fileName;
};

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

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

private:
    const QString m_branchName;
};

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

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

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

private:
209
210
    GitClient *m_client;
    QString m_workingDirectory;
211
    QString m_id;
212
213
};

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

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

        setBaseArguments(args);
237
238
    }

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

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

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

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
286
287
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()
    {
288
        m_client->log(m_workingDirectory, m_fileNames, m_enableAnnotationContextMenu, arguments());
289
290
291
292
293
294
295
296
297
    }

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

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

306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
// 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
326
static inline VcsBase::VcsBaseOutputWindow *outputWindow()
327
{
hjk's avatar
hjk committed
328
    return VcsBase::VcsBaseOutputWindow::instance();
329
330
}

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

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

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

346
// ---------------- GitClient
347
348
349

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

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

GitClient::~GitClient()
{
}

364
const char *GitClient::noColorOption = "--no-color";
365
const char *GitClient::decorateOption = "--decorate";
366

con's avatar
con committed
367
368
QString GitClient::findRepositoryForDirectory(const QString &dir)
{
Tobias Hunger's avatar
Tobias Hunger committed
369
    if (gitVersion(true) >= 0x010700) {
370
371
372
373
374
375
376
377
378
379
380
381
382
383
        // 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
384
385
386
        QByteArray outputText;
        QStringList arguments;
        arguments << QLatin1String("rev-parse") << QLatin1String("--show-toplevel");
387
        fullySynchronousGit(directory.absolutePath(), arguments, &outputText, 0, false);
388
        return QString::fromLocal8Bit(outputText.trimmed());
Orgad Shaneh's avatar
Orgad Shaneh committed
389
390
391
392
393
    } else {
        // Check for ".git/config"
        const QString checkFile = QLatin1String(GIT_DIRECTORY) + QLatin1String("/config");
        return VcsBase::VcsBasePlugin::findRepositoryForDirectory(dir, checkFile);
    }
con's avatar
con committed
394
395
}

hjk's avatar
hjk committed
396
VcsBase::VcsBaseEditorWidget *GitClient::findExistingVCSEditor(const char *registerDynamicProperty,
Tobias Hunger's avatar
Tobias Hunger committed
397
                                                               const QString &dynamicPropertyValue) const
398
{
hjk's avatar
hjk committed
399
    VcsBase::VcsBaseEditorWidget *rc = 0;
hjk's avatar
hjk committed
400
    Core::IEditor *outputEditor = locateEditor(registerDynamicProperty, dynamicPropertyValue);
401
402
403
    if (!outputEditor)
        return 0;

404
    // Exists already
hjk's avatar
hjk committed
405
    Core::EditorManager::activateEditor(outputEditor, Core::EditorManager::ModeSwitch);
406
    outputEditor->createNew(m_msgWait);
hjk's avatar
hjk committed
407
    rc = VcsBase::VcsBaseEditorWidget::getVcsBaseEditor(outputEditor);
408
409
410
411

    return rc;
}

con's avatar
con committed
412
413
414
415
/* 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
416
VcsBase::VcsBaseEditorWidget *GitClient::createVcsEditor(const Core::Id &id,
Tobias Hunger's avatar
Tobias Hunger committed
417
418
419
                                                         QString title,
                                                         // Source file or directory
                                                         const QString &source,
420
                                                         CodecType codecType,
Tobias Hunger's avatar
Tobias Hunger committed
421
422
423
424
                                                         // Dynamic property and value to identify that editor
                                                         const char *registerDynamicProperty,
                                                         const QString &dynamicPropertyValue,
                                                         QWidget *configWidget) const
con's avatar
con committed
425
{
hjk's avatar
hjk committed
426
    VcsBase::VcsBaseEditorWidget *rc = 0;
427
    QTC_CHECK(!findExistingVCSEditor(registerDynamicProperty, dynamicPropertyValue));
428
429

    // Create new, set wait message, set up with source and codec
hjk's avatar
hjk committed
430
    Core::IEditor *outputEditor = Core::EditorManager::openEditorWithContents(id, &title, m_msgWait);
431
    outputEditor->document()->setProperty(registerDynamicProperty, dynamicPropertyValue);
hjk's avatar
hjk committed
432
    rc = VcsBase::VcsBaseEditorWidget::getVcsBaseEditor(outputEditor);
433
434
435
436
    connect(rc, SIGNAL(annotateRevisionRequested(QString,QString,int)),
            this, SLOT(slotBlameRevisionRequested(QString,QString,int)));
    QTC_ASSERT(rc, return 0);
    rc->setSource(source);
437
    if (codecType == CodecSource) {
438
        rc->setCodec(getSourceCodec(source));
439
440
441
442
443
444
    } else if (codecType == CodecLogOutput) {
        QString encodingName = readConfigValue(source, QLatin1String("i18n.logOutputEncoding"));
        if (encodingName.isEmpty())
            encodingName = QLatin1String("utf-8");
        rc->setCodec(QTextCodec::codecForName(encodingName.toLocal8Bit()));
    }
445

446
    rc->setForceReadOnly(true);
hjk's avatar
hjk committed
447
    Core::EditorManager::activateEditor(outputEditor, Core::EditorManager::ModeSwitch);
448
449
450
451

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

con's avatar
con committed
452
453
454
    return rc;
}

455
456
void GitClient::diff(const QString &workingDirectory,
                     const QStringList &diffArgs,
457
458
                     const QStringList &unstagedFileNames,
                     const QStringList &stagedFileNames)
con's avatar
con committed
459
{
460
    const QString binary = settings()->stringValue(GitSettings::binaryPathKey);
hjk's avatar
hjk committed
461
    const Core::Id editorId = Git::Constants::GIT_DIFF_EDITOR_ID;
con's avatar
con committed
462
463
    const QString title = tr("Git Diff");

hjk's avatar
hjk committed
464
    VcsBase::VcsBaseEditorWidget *editor = findExistingVCSEditor("originalFileName", workingDirectory);
465
466
    if (!editor) {
        GitCommitDiffArgumentsWidget *argWidget =
467
                new GitCommitDiffArgumentsWidget(this, workingDirectory, diffArgs,
468
469
                                                 unstagedFileNames, stagedFileNames);

hjk's avatar
hjk committed
470
        editor = createVcsEditor(editorId, title,
471
                                 workingDirectory, CodecSource, "originalFileName", workingDirectory, argWidget);
hjk's avatar
hjk committed
472
        connect(editor, SIGNAL(diffChunkReverted(VcsBase::DiffChunk)), argWidget, SLOT(executeCommand()));
473
    }
474
475
476

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

479
480
481
    // 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
482
    VcsBase::Command *command = createCommand(workingDirectory, editor);
483
    // Directory diff?
484
485
486
487

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

488
489
    int timeout = settings()->intValue(GitSettings::timeoutKey);

490
    if (unstagedFileNames.empty() && stagedFileNames.empty()) {
491
492
       QStringList arguments(cmdArgs);
       arguments << userDiffArgs;
493
       outputWindow()->appendCommand(workingDirectory, binary, arguments);
494
       command->addJob(arguments, timeout);
495
496
497
    } else {
        // Files diff.
        if (!unstagedFileNames.empty()) {
498
499
           QStringList arguments(cmdArgs);
           arguments << userDiffArgs;
500
           arguments << QLatin1String("--") << unstagedFileNames;
501
           outputWindow()->appendCommand(workingDirectory, binary, arguments);
502
           command->addJob(arguments, timeout);
503
504
        }
        if (!stagedFileNames.empty()) {
505
506
           QStringList arguments(cmdArgs);
           arguments << userDiffArgs;
507
           arguments << QLatin1String("--cached") << diffArgs << QLatin1String("--") << stagedFileNames;
508
           outputWindow()->appendCommand(workingDirectory, binary, arguments);
509
           command->addJob(arguments, timeout);
510
511
512
        }
    }
    command->execute();
con's avatar
con committed
513
514
}

515
516
517
void GitClient::diff(const QString &workingDirectory,
                     const QStringList &diffArgs,
                     const QString &fileName)
con's avatar
con committed
518
{
hjk's avatar
hjk committed
519
    const Core::Id editorId = Git::Constants::GIT_DIFF_EDITOR_ID;
Tobias Hunger's avatar
Tobias Hunger committed
520
    const QString title = tr("Git Diff \"%1\"").arg(fileName);
hjk's avatar
hjk committed
521
    const QString sourceFile = VcsBase::VcsBaseEditorWidget::getSource(workingDirectory, fileName);
522

hjk's avatar
hjk committed
523
    VcsBase::VcsBaseEditorWidget *editor = findExistingVCSEditor("originalFileName", sourceFile);
524
525
    if (!editor) {
        GitFileDiffArgumentsWidget *argWidget =
526
                new GitFileDiffArgumentsWidget(this, workingDirectory, diffArgs, fileName);
527

hjk's avatar
hjk committed
528
529
        editor = createVcsEditor(editorId, title, sourceFile, CodecSource, "originalFileName", sourceFile, argWidget);
        connect(editor, SIGNAL(diffChunkReverted(VcsBase::DiffChunk)), argWidget, SLOT(executeCommand()));
530
    }
Tobias Hunger's avatar
Tobias Hunger committed
531
    editor->setDiffBaseDirectory(workingDirectory);
532

533
534
535
    GitFileDiffArgumentsWidget *argWidget = qobject_cast<GitFileDiffArgumentsWidget *>(editor->configurationWidget());
    QStringList userDiffArgs = argWidget->arguments();

536
537
538
539
540
541
542
    QStringList cmdArgs;
    cmdArgs << QLatin1String("diff") << QLatin1String(noColorOption)
              << userDiffArgs;

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

545
546
547
548
void GitClient::diffBranch(const QString &workingDirectory,
                           const QStringList &diffArgs,
                           const QString &branchName)
{
hjk's avatar
hjk committed
549
    const Core::Id editorId = Git::Constants::GIT_DIFF_EDITOR_ID;
Tobias Hunger's avatar
Tobias Hunger committed
550
    const QString title = tr("Git Diff Branch \"%1\"").arg(branchName);
hjk's avatar
hjk committed
551
    const QString sourceFile = VcsBase::VcsBaseEditorWidget::getSource(workingDirectory, QStringList());
552

hjk's avatar
hjk committed
553
    VcsBase::VcsBaseEditorWidget *editor = findExistingVCSEditor("BranchName", branchName);
554
    if (!editor)
hjk's avatar
hjk committed
555
        editor = createVcsEditor(editorId, title, sourceFile, CodecSource, "BranchName", branchName,
556
                                 new GitBranchDiffArgumentsWidget(this, workingDirectory,
557
                                                                  diffArgs, branchName));
Tobias Hunger's avatar
Tobias Hunger committed
558
    editor->setDiffBaseDirectory(workingDirectory);
559

560
561
    GitBranchDiffArgumentsWidget *argWidget = qobject_cast<GitBranchDiffArgumentsWidget *>(editor->configurationWidget());
    QStringList userDiffArgs = argWidget->arguments();
562
563
564

    QStringList cmdArgs;
    cmdArgs << QLatin1String("diff") << QLatin1String(noColorOption)
565
              << userDiffArgs  << branchName;
566
567

    executeGit(workingDirectory, cmdArgs, editor);
568
569
}

con's avatar
con committed
570
571
void GitClient::status(const QString &workingDirectory)
{
572
    // @TODO: Use "--no-color" once it is supported
573
574
    QStringList statusArgs(QLatin1String("status"));
    statusArgs << QLatin1String("-u");
hjk's avatar
hjk committed
575
    VcsBase::VcsBaseOutputWindow *outwin = outputWindow();
576
    outwin->setRepository(workingDirectory);
hjk's avatar
hjk committed
577
    VcsBase::Command *command = executeGit(workingDirectory, statusArgs, 0, true);
578
    connect(command, SIGNAL(finished(bool,int,QVariant)), outwin, SLOT(clearRepository()),
579
            Qt::QueuedConnection);
con's avatar
con committed
580
581
}

582
static const char graphLogFormatC[] = "%h %d %an %s %ci";
583
584

// Create a graphical log.
585
void GitClient::graphLog(const QString &workingDirectory, const QString & branch)
586
587
588
589
{
    QStringList arguments;
    arguments << QLatin1String("log") << QLatin1String(noColorOption);

590
591
592
    int logCount = settings()->intValue(GitSettings::logCountKey);
    if (logCount > 0)
         arguments << QLatin1String("-n") << QString::number(logCount);
593
594
595
    arguments << (QLatin1String("--pretty=format:") +  QLatin1String(graphLogFormatC))
              << QLatin1String("--topo-order") <<  QLatin1String("--graph");

596
597
598
599
    QString title;
    if (branch.isEmpty()) {
        title = tr("Git Log");
    } else {
Tobias Hunger's avatar
Tobias Hunger committed
600
        title = tr("Git Log \"%1\"").arg(branch);
601
602
        arguments << branch;
    }
hjk's avatar
hjk committed
603
    const Core::Id editorId = Git::Constants::GIT_LOG_EDITOR_ID;
hjk's avatar
hjk committed
604
605
    const QString sourceFile = VcsBase::VcsBaseEditorWidget::getSource(workingDirectory, QStringList());
    VcsBase::VcsBaseEditorWidget *editor = findExistingVCSEditor("logFileName", sourceFile);
606
    if (!editor)
hjk's avatar
hjk committed
607
        editor = createVcsEditor(editorId, title, sourceFile, CodecLogOutput, "logFileName", sourceFile, 0);
608
609
610
    executeGit(workingDirectory, arguments, editor);
}

611
void GitClient::log(const QString &workingDirectory, const QStringList &fileNames,
612
                    bool enableAnnotationContextMenu, const QStringList &args)
con's avatar
con committed
613
{
614
    const QString msgArg = fileNames.empty() ? workingDirectory :
615
                           fileNames.join(QLatin1String(", "));
616
617
    const QString title = tr("Git Log \"%1\"").arg(msgArg);
    const Core::Id editorId = Git::Constants::GIT_LOG_EDITOR_ID;
hjk's avatar
hjk committed
618
619
    const QString sourceFile = VcsBase::VcsBaseEditorWidget::getSource(workingDirectory, fileNames);
    VcsBase::VcsBaseEditorWidget *editor = findExistingVCSEditor("logFileName", sourceFile);
620
    if (!editor)
hjk's avatar
hjk committed
621
        editor = createVcsEditor(editorId, title, sourceFile, CodecLogOutput, "logFileName", sourceFile,
622
623
624
625
626
                                 new GitLogArgumentsWidget(this, workingDirectory,
                                                           enableAnnotationContextMenu,
                                                           args, fileNames));
    editor->setFileLogAnnotateEnabled(enableAnnotationContextMenu);

627
    QStringList arguments;
628
629
    arguments << QLatin1String("log") << QLatin1String(noColorOption)
              << QLatin1String(decorateOption);
630

631
632
633
    int logCount = settings()->intValue(GitSettings::logCountKey);
    if (logCount > 0)
         arguments << QLatin1String("-n") << QString::number(logCount);
634

635
636
637
638
639
    GitLogArgumentsWidget *argWidget = qobject_cast<GitLogArgumentsWidget *>(editor->configurationWidget());
    QStringList userArgs = argWidget->arguments();

    arguments.append(userArgs);

640
641
    if (!fileNames.isEmpty())
        arguments.append(fileNames);
con's avatar
con committed
642

643
    executeGit(workingDirectory, arguments, editor);
con's avatar
con committed
644
645
}

646
647
648
649
650
651
652
653
654
655
656
657
// 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
658
    return GitClient::tr("Cannot describe \"%1\".").arg(sha);
659
660
}

661
void GitClient::show(const QString &source, const QString &id, const QStringList &args)
con's avatar
con committed
662
{
663
664
665
666
667
    if (!canShow(id)) {
        outputWindow()->append(msgCannotShow(id));
        return;
    }

Tobias Hunger's avatar
Tobias Hunger committed
668
    const QString title = tr("Git Show \"%1\"").arg(id);
hjk's avatar
hjk committed
669
    const Core::Id editorId = Git::Constants::GIT_DIFF_EDITOR_ID;
hjk's avatar
hjk committed
670
    VcsBase::VcsBaseEditorWidget *editor = findExistingVCSEditor("show", id);
671
    if (!editor)
hjk's avatar
hjk committed
672
        editor = createVcsEditor(editorId, title, source, CodecSource, "show", id,
673
                                 new GitShowArgumentsWidget(this, source, args, id));
674
675
676

    GitShowArgumentsWidget *argWidget = qobject_cast<GitShowArgumentsWidget *>(editor->configurationWidget());
    QStringList userArgs = argWidget->arguments();
677
678
679

    QStringList arguments;
    arguments << QLatin1String("show") << QLatin1String(noColorOption);
680
    arguments << QLatin1String(decorateOption);
681
682
    arguments.append(userArgs);
    arguments << id;
con's avatar
con committed
683
684
685

    const QFileInfo sourceFi(source);
    const QString workDir = sourceFi.isDir() ? sourceFi.absoluteFilePath() : sourceFi.absolutePath();
Tobias Hunger's avatar
Tobias Hunger committed
686
    editor->setDiffBaseDirectory(workDir);
687
    executeGit(workDir, arguments, editor);
con's avatar
con committed
688
689
}

Tobias Hunger's avatar
Tobias Hunger committed
690
691
void GitClient::saveSettings()
{
hjk's avatar
hjk committed
692
    settings()->writeSettings(Core::ICore::settings());
Tobias Hunger's avatar
Tobias Hunger committed
693
694
}

695
696
697
698
699
700
701
702
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);
703
    blame(fi.absolutePath(), QStringList(), fi.fileName(), change, lineNumber);
704
705
}

706
707
708
709
710
711
712
713
714
715
716
717
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());
}

718
719
720
721
722
723
724
725
726
727
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());
}

728
void GitClient::blame(const QString &workingDirectory,
729
                      const QStringList &args,
730
                      const QString &fileName,
Tobias Hunger's avatar
Tobias Hunger committed
731
732
                      const QString &revision,
                      int lineNumber)
con's avatar
con committed
733
{
hjk's avatar
hjk committed
734
    const Core::Id editorId = Git::Constants::GIT_BLAME_EDITOR_ID;
hjk's avatar
hjk committed
735
    const QString id = VcsBase::VcsBaseEditorWidget::getTitleId(workingDirectory, QStringList(fileName), revision);
Tobias Hunger's avatar
Tobias Hunger committed
736
    const QString title = tr("Git Blame \"%1\"").arg(id);
hjk's avatar
hjk committed
737
    const QString sourceFile = VcsBase::VcsBaseEditorWidget::getSource(workingDirectory, fileName);
con's avatar
con committed
738

hjk's avatar
hjk committed
739
    VcsBase::VcsBaseEditorWidget *editor = findExistingVCSEditor("blameFileName", id);
740
741
    if (!editor) {
        GitBlameArgumentsWidget *argWidget =
742
                new GitBlameArgumentsWidget(this, workingDirectory, args,
743
                                            revision, fileName);
hjk's avatar
hjk committed
744
        editor = createVcsEditor(editorId, title, sourceFile, CodecSource, "blameFileName", id, argWidget);
745
746
747
        argWidget->setEditor(editor);
    }

748
749
750
    GitBlameArgumentsWidget *argWidget = qobject_cast<GitBlameArgumentsWidget *>(editor->configurationWidget());
    QStringList userBlameArgs = argWidget->arguments();

751
752
753
754
755
756
    QStringList arguments(QLatin1String("blame"));
    arguments << QLatin1String("--root");
    arguments.append(userBlameArgs);
    arguments << QLatin1String("--") << fileName;
    if (!revision.isEmpty())
        arguments << revision;
hjk's avatar
hjk committed
757
    executeGit(workingDirectory, arguments, editor, false, VcsBase::Command::NoReport, lineNumber);
con's avatar
con committed
758
759
}

760
761
762
763
void GitClient::checkoutBranch(const QString &workingDirectory, const QString &branch)
{
    QStringList arguments(QLatin1String("checkout"));
    arguments <<  branch;
hjk's avatar
hjk committed
764
    VcsBase::Command *cmd = executeGit(workingDirectory, arguments, 0, true);
765
    connectRepositoryChanged(workingDirectory, cmd);
766
767
}

768
bool GitClient::synchronousCheckoutBranch(const QString &workingDirectory,
Tobias Hunger's avatar
Tobias Hunger committed
769
770
                                          const QString &branch,
                                          QString *errorMessage /* = 0 */)
771
772
773
774
775
{
    QByteArray outputText;
    QByteArray errorText;
    QStringList arguments;
    arguments << QLatin1String("checkout") << branch;
776
    const bool rc = fullySynchronousGit(workingDirectory, arguments, &outputText, &errorText);
777
    const QString output = commandOutputFromLocal8Bit(outputText);
778
    outputWindow()->append(output);
779
780
    if (!rc) {
        const QString stdErr = commandOutputFromLocal8Bit(errorText);
Friedemann Kleint's avatar
Friedemann Kleint committed
781
        //: Meaning of the arguments: %1: Branch, %2: Repository, %3: Error message
Tobias Hunger's avatar
Tobias Hunger committed
782
        const QString msg = tr("Cannot checkout \"%1\" of \"%2\": %3").arg(branch, workingDirectory, stdErr);
783
784
785
        if (errorMessage) {
            *errorMessage = msg;
        } else {
786
            outputWindow()->appendError(msg);
787
788
789
790
791
792
        }
        return false;
    }
    return true;
}

con's avatar
con committed
793
794
795
796
797
798
799
800
801
802
803
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;

804
    executeGit(workingDirectory, arguments, 0, true);
con's avatar
con committed
805
806
807
808
809
810
811
812
813
}

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

hjk's avatar
hjk committed
814
    VcsBase::Command *cmd = executeGit(workingDirectory, arguments, 0, true);
815
    connectRepositoryChanged(workingDirectory, cmd);
con's avatar
con committed
816
817
818
819
820
821
822
}

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

823
    executeGit(workingDirectory, arguments, 0, true);
con's avatar
con committed
824
825
}

826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
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));
        if (errorMessageIn) {
            *errorMessageIn = errorMessage;
        } else {
            outputWindow()->appendError(errorMessage);
        }
    }
    return rc;
}

850
851
852
853
// 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
854
855
856
857
{
    QByteArray outputText;
    QByteArray errorText;
    QStringList arguments;
858
859
860
861
    arguments << QLatin1String("add");
    if (intendToAdd)
        arguments << QLatin1String("--intent-to-add");
    arguments.append(files);
862
    const bool rc = fullySynchronousGit(workingDirectory, arguments, &outputText, &errorText);
con's avatar
con committed
863
    if (!rc) {
Tobias Hunger's avatar
Tobias Hunger committed
864
        const QString errorMessage = tr("Cannot add %n file(s) to \"%1\": %2", 0, files.size()).
865
866
                                     arg(QDir::toNativeSeparators(workingDirectory),
                                     commandOutputFromLocal8Bit(errorText));
867
        outputWindow()->appendError(errorMessage);
con's avatar
con committed
868
869
870
871
    }
    return rc;
}

872
873
874
875
876
877
878
879
880
881
882
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);
883
    const bool rc = fullySynchronousGit(workingDirectory, arguments, &outputText, &errorText);
884
    if (!rc) {
Tobias Hunger's avatar
Tobias Hunger committed
885
        const QString errorMessage = tr("Cannot remove %n file(s) from \"%1\": %2", 0, files.size()).
886
                                     arg(QDir::toNativeSeparators(workingDirectory), commandOutputFromLocal8Bit(errorText));
887
        outputWindow()->appendError(errorMessage);
888
889
890
891
    }
    return rc;
}

dt's avatar
dt committed
892
893
894
895
896
897
898
899
900
901
bool GitClient::synchronousMove(const QString &workingDirectory,
                                const QString &from,
                                const QString &to)
{
    QByteArray outputText;
    QByteArray errorText;
    QStringList arguments;
    arguments << QLatin1String("mv");
    arguments << (from);
    arguments << (to);
902
    const bool rc = fullySynchronousGit(workingDirectory, arguments, &outputText, &errorText);
dt's avatar
dt committed
903
    if (!rc) {
Tobias Hunger's avatar
Tobias Hunger committed
904
        const QString errorMessage = tr("Cannot move from \"%1\" to \"%2\": %3").
dt's avatar
dt committed
905
906
907
908
909
910
                                     arg(from, to, commandOutputFromLocal8Bit(errorText));
        outputWindow()->appendError(errorMessage);
    }
    return rc;
}

911
912
913
bool GitClient::synchronousReset(const QString &workingDirectory,
                                 const QStringList &files,
                                 QString *err