gitclient.cpp 101 KB
Newer Older
hjk's avatar
hjk committed
1
/****************************************************************************
con's avatar
con committed
2
**
3
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
hjk's avatar
hjk committed
4
** Contact: http://www.qt-project.org/legal
con's avatar
con committed
5
**
hjk's avatar
hjk committed
6
** This file is part of Qt Creator.
con's avatar
con committed
7
**
hjk's avatar
hjk committed
8
9
10
11
12
13
14
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia.  For licensing terms and
** conditions see http://qt.digia.com/licensing.  For further information
** use the contact form at http://qt.digia.com/contact-us.
15
**
16
** GNU Lesser General Public License Usage
hjk's avatar
hjk committed
17
18
19
20
21
22
23
24
25
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights.  These rights are described in the Digia Qt LGPL Exception
con's avatar
con committed
26
27
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
hjk's avatar
hjk committed
28
****************************************************************************/
hjk's avatar
hjk committed
29

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

con's avatar
con committed
33
#include "commitdata.h"
hjk's avatar
hjk committed
34
35
#include "gitconstants.h"
#include "gitplugin.h"
36
#include "gitsubmiteditor.h"
37
#include "gitversioncontrol.h"
38
#include "mergetool.h"
con's avatar
con committed
39

40
41
#include <vcsbase/submitfilemodel.h>

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
#include <QComboBox>
#include <QMessageBox>
76
#include <QPushButton>
77
78
#include <QToolButton>
#include <QTextCodec>
con's avatar
con committed
79

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

82
83
84
namespace Git {
namespace Internal {

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

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

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

        setBaseArguments(args);
106
107
    }

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

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

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

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

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

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

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

private:
    const QString m_fileName;
};

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

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

private:
    const QString m_branchName;
};

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

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

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

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

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

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

        setBaseArguments(args);
236
237
    }

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

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

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

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

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

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

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

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

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

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

345
// ---------------- GitClient
346
347
348

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

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

GitClient::~GitClient()
{
}

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

con's avatar
con committed
366
367
QString GitClient::findRepositoryForDirectory(const QString &dir)
{
Orgad Shaneh's avatar
Orgad Shaneh committed
368
369
370
371
372
373
374
375
376
    // 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;
377

Orgad Shaneh's avatar
Orgad Shaneh committed
378
379
380
        if (directory.exists())
            break;
    } while (directory.cdUp());
381

Orgad Shaneh's avatar
Orgad Shaneh committed
382
383
384
385
386
    QByteArray outputText;
    QStringList arguments;
    arguments << QLatin1String("rev-parse") << QLatin1String("--show-toplevel");
    fullySynchronousGit(directory.absolutePath(), arguments, &outputText, 0, false);
    return QString::fromLocal8Bit(outputText.trimmed());
con's avatar
con committed
387
388
}

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

hjk's avatar
hjk committed
405
VcsBase::VcsBaseEditorWidget *GitClient::findExistingVCSEditor(const char *registerDynamicProperty,
Tobias Hunger's avatar
Tobias Hunger committed
406
                                                               const QString &dynamicPropertyValue) const
407
{
hjk's avatar
hjk committed
408
    VcsBase::VcsBaseEditorWidget *rc = 0;
hjk's avatar
hjk committed
409
    Core::IEditor *outputEditor = locateEditor(registerDynamicProperty, dynamicPropertyValue);
410
411
412
    if (!outputEditor)
        return 0;

413
    // Exists already
hjk's avatar
hjk committed
414
    Core::EditorManager::activateEditor(outputEditor, Core::EditorManager::ModeSwitch);
415
    outputEditor->createNew(m_msgWait);
hjk's avatar
hjk committed
416
    rc = VcsBase::VcsBaseEditorWidget::getVcsBaseEditor(outputEditor);
417
418
419
420

    return rc;
}

con's avatar
con committed
421
422
423
424
/* 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
425
VcsBase::VcsBaseEditorWidget *GitClient::createVcsEditor(const Core::Id &id,
Tobias Hunger's avatar
Tobias Hunger committed
426
427
428
                                                         QString title,
                                                         // Source file or directory
                                                         const QString &source,
429
                                                         CodecType codecType,
Tobias Hunger's avatar
Tobias Hunger committed
430
431
432
433
                                                         // Dynamic property and value to identify that editor
                                                         const char *registerDynamicProperty,
                                                         const QString &dynamicPropertyValue,
                                                         QWidget *configWidget) const
con's avatar
con committed
434
{
hjk's avatar
hjk committed
435
    VcsBase::VcsBaseEditorWidget *rc = 0;
436
    QTC_CHECK(!findExistingVCSEditor(registerDynamicProperty, dynamicPropertyValue));
437
438

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

455
    rc->setForceReadOnly(true);
hjk's avatar
hjk committed
456
    Core::EditorManager::activateEditor(outputEditor, Core::EditorManager::ModeSwitch);
457
458
459
460

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

con's avatar
con committed
461
462
463
    return rc;
}

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

hjk's avatar
hjk committed
473
    VcsBase::VcsBaseEditorWidget *editor = findExistingVCSEditor("originalFileName", workingDirectory);
474
475
    if (!editor) {
        GitCommitDiffArgumentsWidget *argWidget =
476
                new GitCommitDiffArgumentsWidget(this, workingDirectory, diffArgs,
477
478
                                                 unstagedFileNames, stagedFileNames);

hjk's avatar
hjk committed
479
        editor = createVcsEditor(editorId, title,
480
                                 workingDirectory, CodecSource, "originalFileName", workingDirectory, argWidget);
hjk's avatar
hjk committed
481
        connect(editor, SIGNAL(diffChunkReverted(VcsBase::DiffChunk)), argWidget, SLOT(executeCommand()));
482
    }
483
484
485

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

488
489
490
    // 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
491
    VcsBase::Command *command = createCommand(workingDirectory, editor);
492
    // Directory diff?
493
494
495
496

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

497
498
    int timeout = settings()->intValue(GitSettings::timeoutKey);

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

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

hjk's avatar
hjk committed
532
    VcsBase::VcsBaseEditorWidget *editor = findExistingVCSEditor("originalFileName", sourceFile);
533
534
    if (!editor) {
        GitFileDiffArgumentsWidget *argWidget =
535
                new GitFileDiffArgumentsWidget(this, workingDirectory, diffArgs, fileName);
536

hjk's avatar
hjk committed
537
538
        editor = createVcsEditor(editorId, title, sourceFile, CodecSource, "originalFileName", sourceFile, argWidget);
        connect(editor, SIGNAL(diffChunkReverted(VcsBase::DiffChunk)), argWidget, SLOT(executeCommand()));
539
    }
Tobias Hunger's avatar
Tobias Hunger committed
540
    editor->setDiffBaseDirectory(workingDirectory);
541

542
543
544
    GitFileDiffArgumentsWidget *argWidget = qobject_cast<GitFileDiffArgumentsWidget *>(editor->configurationWidget());
    QStringList userDiffArgs = argWidget->arguments();

545
546
547
548
549
550
551
    QStringList cmdArgs;
    cmdArgs << QLatin1String("diff") << QLatin1String(noColorOption)
              << userDiffArgs;

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

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

hjk's avatar
hjk committed
562
    VcsBase::VcsBaseEditorWidget *editor = findExistingVCSEditor("BranchName", branchName);
563
    if (!editor)
hjk's avatar
hjk committed
564
        editor = createVcsEditor(editorId, title, sourceFile, CodecSource, "BranchName", branchName,
565
                                 new GitBranchDiffArgumentsWidget(this, workingDirectory,
566
                                                                  diffArgs, branchName));
Tobias Hunger's avatar
Tobias Hunger committed
567
    editor->setDiffBaseDirectory(workingDirectory);
568

569
570
    GitBranchDiffArgumentsWidget *argWidget = qobject_cast<GitBranchDiffArgumentsWidget *>(editor->configurationWidget());
    QStringList userDiffArgs = argWidget->arguments();
571
572
573

    QStringList cmdArgs;
    cmdArgs << QLatin1String("diff") << QLatin1String(noColorOption)
574
              << userDiffArgs  << branchName;
575
576

    executeGit(workingDirectory, cmdArgs, editor);
577
578
}

579
580
581
582
583
584
585
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
586
587
void GitClient::status(const QString &workingDirectory)
{
588
    // @TODO: Use "--no-color" once it is supported
589
590
    QStringList statusArgs(QLatin1String("status"));
    statusArgs << QLatin1String("-u");
hjk's avatar
hjk committed
591
    VcsBase::VcsBaseOutputWindow *outwin = outputWindow();
592
    outwin->setRepository(workingDirectory);
hjk's avatar
hjk committed
593
    VcsBase::Command *command = executeGit(workingDirectory, statusArgs, 0, true);
594
    connect(command, SIGNAL(finished(bool,int,QVariant)), outwin, SLOT(clearRepository()),
595
            Qt::QueuedConnection);
con's avatar
con committed
596
597
}

598
static const char graphLogFormatC[] = "%h %d %an %s %ci";
599
600

// Create a graphical log.
601
void GitClient::graphLog(const QString &workingDirectory, const QString & branch)
602
603
604
605
{
    QStringList arguments;
    arguments << QLatin1String("log") << QLatin1String(noColorOption);

606
607
608
    int logCount = settings()->intValue(GitSettings::logCountKey);
    if (logCount > 0)
         arguments << QLatin1String("-n") << QString::number(logCount);
609
610
611
    arguments << (QLatin1String("--pretty=format:") +  QLatin1String(graphLogFormatC))
              << QLatin1String("--topo-order") <<  QLatin1String("--graph");

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

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

643
    QStringList arguments;
644
645
    arguments << QLatin1String("log") << QLatin1String(noColorOption)
              << QLatin1String(decorateOption);
646

647
648
649
    int logCount = settings()->intValue(GitSettings::logCountKey);
    if (logCount > 0)
         arguments << QLatin1String("-n") << QString::number(logCount);
650

651
652
653
654
655
    GitLogArgumentsWidget *argWidget = qobject_cast<GitLogArgumentsWidget *>(editor->configurationWidget());
    QStringList userArgs = argWidget->arguments();

    arguments.append(userArgs);

656
    if (!fileNames.isEmpty())
657
        arguments << QLatin1String("--") << fileNames;
con's avatar
con committed
658

659
    executeGit(workingDirectory, arguments, editor);
con's avatar
con committed
660
661
}

662
663
664
665
666
667
668
669
670
671
672
673
// 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
674
    return GitClient::tr("Cannot describe \"%1\".").arg(sha);
675
676
}

677
void GitClient::show(const QString &source, const QString &id, const QStringList &args)
con's avatar
con committed
678
{
679
680
681
682
683
    if (!canShow(id)) {
        outputWindow()->append(msgCannotShow(id));
        return;
    }

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

    GitShowArgumentsWidget *argWidget = qobject_cast<GitShowArgumentsWidget *>(editor->configurationWidget());
    QStringList userArgs = argWidget->arguments();
693
694
695

    QStringList arguments;
    arguments << QLatin1String("show") << QLatin1String(noColorOption);
696
    arguments << QLatin1String(decorateOption);
697
698
    arguments.append(userArgs);
    arguments << id;
con's avatar
con committed
699
700
701

    const QFileInfo sourceFi(source);
    const QString workDir = sourceFi.isDir() ? sourceFi.absoluteFilePath() : sourceFi.absolutePath();
Tobias Hunger's avatar
Tobias Hunger committed
702
    editor->setDiffBaseDirectory(workDir);
703
    executeGit(workDir, arguments, editor);
con's avatar
con committed
704
705
}

Tobias Hunger's avatar
Tobias Hunger committed
706
707
void GitClient::saveSettings()
{
hjk's avatar
hjk committed
708
    settings()->writeSettings(Core::ICore::settings());
Tobias Hunger's avatar
Tobias Hunger committed
709
710
}

711
712
713
714
715
716
717
718
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);
719
    blame(fi.absolutePath(), QStringList(), fi.fileName(), change, lineNumber);
720
721
}

722
723
724
725
726
727
728
729
730
731
732
733
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());
}

734
735
736
737
738
739
740
741
742
743
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());
}

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

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

764
765
766
    GitBlameArgumentsWidget *argWidget = qobject_cast<GitBlameArgumentsWidget *>(editor->configurationWidget());
    QStringList userBlameArgs = argWidget->arguments();

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

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

con's avatar
con committed
800
801
802
803
804
805
806
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
807
808
809
810
811
812
813
814
815
816
817
818
    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
819
    VcsBase::Command *cmd = executeGit(workingDirectory, arguments, 0, true);
820
    connectRepositoryChanged(workingDirectory, cmd);
con's avatar
con committed
821
822
823
824
825
826
827
}

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

828
    executeGit(workingDirectory, arguments, 0, true);
con's avatar
con committed
829
830
}

831
832
833
834
835
836
837
838
839
840
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) {
Yuchen Deng's avatar
Yuchen Deng committed
841
842
843
844
845
846
847
848
        QString encodingName = readConfigValue(workingDirectory, QLatin1String("i18n.logOutputEncoding"));
        if (encodingName.isEmpty())
            encodingName = QLatin1String("utf-8");
        QTextCodec *codec = QTextCodec::codecForName(encodingName.toLocal8Bit());
        if (codec)
            *output = codec->toUnicode(outputText);
        else
            *output = commandOutputFromLocal8Bit(outputText);
849
850
851
852
    } else {
        const QString errorMessage = tr("Cannot obtain log of \"%1\": %2").
                                     arg(QDir::toNativeSeparators(workingDirectory),
                                         commandOutputFromLocal8Bit(errorText));
853
        if (errorMessageIn)
854
            *errorMessageIn = errorMessage;
855
        else
856
857
858
859
860
            outputWindow()->appendError(errorMessage);
    }
    return rc;
}

861
862
863
864
// 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
865
866
867
868
{
    QByteArray outputText;
    QByteArray errorText;
    QStringList arguments;
869
870
871
872
    arguments << QLatin1String("add");
    if (intendToAdd)
        arguments << QLatin1String("--intent-to-add");
    arguments.append(files);
873
    const bool rc = fullySynchronousGit(workingDirectory, arguments, &outputText, &errorText);
con's avatar
con committed
874
    if (!rc) {
Tobias Hunger's avatar
Tobias Hunger committed
875
        const QString errorMessage = tr("Cannot add %n file(s) to \"%1\": %2", 0, files.size()).
876
877
                                     arg(QDir::toNativeSeparators(workingDirectory),
                                     commandOutputFromLocal8Bit(errorText));
878
        outputWindow()->appendError(errorMessage);
con's avatar
con committed
879
880
881
882
    }
    return rc;
}

883
884
885
886
887
888
889
890
891
892
893
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);
894
    const bool rc = fullySynchronousGit(workingDirectory, arguments, &outputText, &errorText);
895
    if (!rc) {
Tobias Hunger's avatar
Tobias Hunger committed